Thursday, March 13, 2014

What is the Difference between Const and Readonly

Difference between Const and Readonly
  • const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  • const variables can declared in methods ,while readonly fields cannot be declared in methods.
  • const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  • A const field is a compile-time constant, the readonly field can be used for run time constants.
public class Const_VS_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_VS_Readonly()
{
I_RO_VALUE = 3;
}
}


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.

  • class MyClass
  • {
  • static int X = 10;
  • int Y = 20;
  • public static void Show()
  • {
  • Console.WriteLine(X);
  • Console.WriteLine(Y); //error, since you can access only static members
  • }
  • }
  • No comments:

    Post a Comment