Tuesday, 14 December 2010

What is the difference between const and static read-only member?

A const field must be initialized at the place where it is declared as shown in the example below.
class Program
{
      public const int Number = 100;
}
It is a compile time error to declare a const without a value. The code below will generate a compiler error stating "A const field requires a value to be provided"
class Program
{
      public const int Number;
}
It is a compile time error to change the value of a constant. The following code will generate a compiler error stating "The left-hand side of an assignment must be a variable, property or indexer"
class Program
{
     public const int Number = 100;
     static void Main()
     {
           Number = 200;
     }
}

No comments:

Post a Comment