Search This Blog

Thursday, November 7, 2013

const c#

C# > Modifiers > const

The const specifies that the value of the field or the local variable is constant and it cannot be modified.
 
The const keyword differs from the readonly keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor.

Example:

class SampleConst
    {
        public int x;
        public int y;
        public const int c1 = 1;
        public const int c2 = c1 + 5;

        public SampleConst(int v1)
        {
            x = v1 + c1;
            y = x + c2;
        }
    }