Constant,readonly and static discussion

Constant

1)      It is assigned a value at time of declaration but not modified at any time. By default constant is static, hence cannot define as static.const field is a compile time constant. It is fully evaluated at compile time.const keyword to built-in value types (byte, short, int, char, float, decimal etc.), enum, string or reference types which can be assigned with a null value. Constants can be marked as public, private, protected, internal, or protected internal access modifiers. Use the const modifier when we sure that the value a field or local variable would not be changed.

Readonly

2)      A readonly field can be initialized either at the time of declaration or within the constructor of same class. Therefore, readonly fields can be used for run-time constants.bydefault it is not static and can declare as a static member. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly. Use the readonly modifier when we want to make a field constant at run time.readonly declare only in class level but can change value in constructor level, and constant declare in class or method level but not change.

Static

3) The static keyword is used to specify a static member, which means static members are common to   all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. Static class cannot be inherit .

Static constructors

  • A given class may define only a single static constructor. In other words, the static Constructor cannot be overloaded.
  • A static constructor does not take an access modifier and cannot take any

Parameters.

  • A static constructor executes exactly one time, regardless of how many objects of

the types are created.

  • The runtime invokes the static constructor when it creates an instance of the class

Or before accessing the first static member invoked by the caller.

  • The static constructor executes before any instance-level constructors.

 

class Program

{

public const int X = 10;

const Animal obj2 = new Animal();—-Error

readonly Animal obj21 ;

static void Test(Animal a, int Z)

{

const int X = 10, X1 = 50;

const int Y = X + X1; //no error, since its evaluated a compile time

const Animal obj1 = null;

Animal obj2 = new Animal();//

const int Y1 = X + Z;– Cause InvalidCastException at run time 

}

 

}

  1 comment for “Constant,readonly and static discussion

Leave a Reply