Explain about Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
  1. public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
  1. void Calculate(int Z)
  2. {
  3. const int X = 10, X1 = 50;
  4. const int Y = X + X1; //no error, since its evaluated a compile time
  5. const int Y1 = X + Z; //gives error, since its evaluated at run time
  6. }
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
  1. const MyClass obj1 = null;//no error, since its evaluated a compile time
  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
  1. class MyClass
  2. {
  3. readonly int X = 10; // initialized at the time of declaration
  4. readonly int X1;
  5.  
  6. public MyClass(int x1)
  7. {
  8. X1 = x1; // initialized at run time
  9. }
  10. }
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. 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 you want to make a field constant at run time.

Static

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.
  1. class MyClass
  2. {
  3. static int X = 10;
  4. int Y = 20;
  5. public static void Show()
  6. {
  7. Console.WriteLine(X);
  8. Console.WriteLine(Y); //error, since you can access only static members
  9. }
  10. }

Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can't be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.


    -------------------------------------------------------------------------------------------------------


    These are very common keywords and are quite confusing. So today we will discuss these keywords and try to understand them.
    1. Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

      Csharp-Const-ReadOnly-and-StaticReadOnly1.jpg

      Here I have created a class named Variables and defined all three variables, so first let's play with const.

      Csharp-Const-ReadOnly-and-StaticReadOnly2.jpg

      Here I tried to de-initialize the const variable, it gaves me an error like "A const field requires a value to be provided".  Ok now I initialize a value for this variable and try to change it further in the class.

      Csharp-Const-ReadOnly-and-StaticReadOnly3.jpg

      Here I have created a static constructor, default constructor, parameterized constructor and a Simple Method. I tried to change the value of the const variable everywhere but once I assign the value, I am unable to change it again since when I do it gives me a compile time error as you can see in the snapshot above.

      Now let's on to the readonly keyword.
       
    2. Readonly: Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method. Let's see:

      Csharp-Const-ReadOnly-and-StaticReadOnly4.jpg

      Here first I try to initialize the value in the static constructor. It gives me an error. Which you can see above.
      Now I try to change the value in a method, see what happened:

      Csharp-Const-ReadOnly-and-StaticReadOnly5.jpg
       
      Here, it is also giving an error that you can only assign a value either through a variable or a constructor.
      Now try to change the value in the default constructor.

      Csharp-Const-ReadOnly-and-StaticReadOnly6.jpg
       
      Now in the snapshot above you can see it's built successfully without an error, warning or messages. Let's check if there is a runtime error. OK.

      Csharp-Const-ReadOnly-and-StaticReadOnly7.jpg
       
      Now here we can see that there is not a runtime error and the value was assigned successfully to the Readonly variable.
      Now one gotcha is, now that you have assigned the value, can you change this value again ??? 
      Let's try to change the value again.

      Csharp-Const-ReadOnly-and-StaticReadOnly8.jpg

       
      Here I created  a parameterized constructor and created a new object, and passing a value as "Hello Frend'z" and as I built it, it gave me the result "Build Succeeded".  Now let's move ahead and check for a runtime error:

      Csharp-Const-ReadOnly-and-StaticReadOnly9.jpg
       
      See guys. There is no runtime error !!  And the value can be changed again and again through a constructor.
       
      Now move ahead to Static Readonly variables.
       
    3. Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime. Let's understand it practically.

      Csharp-Const-ReadOnly-and-StaticReadOnly10.jpg

      Now in the preceding you can see that I used two variables, one is not assigned and another is assigned, and the static constructor.  Now in the static constructor you can see that the unassigned variable is being assigned and the assigned value is being changed. And there is no compile time error. Further I try to again change this variable's value.  See what happened:

      Csharp-Const-ReadOnly-and-StaticReadOnly11.jpg
       
      As you can see in the above, I created Default, Parameterized Constructor and Method and tried to change the value again here. But I am getting a compile time error for all.

0 comments:

Post a Comment