Thursday, October 21, 2010

Const Keyword

Const is a keyword which can be use to declare fields. We can initialize Const variable only at the time of declaration and cant modify it at runtime.
We cant make a Const field as static.
Const fields are compile-time constants.

For ex:
I have a class which contains two const variables.
class TestConst
{
public const int a = 10;
public const int b = 7;
}

I have another class, where i have created an object of TestConst class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestConst.a);
Console.WriteLine(TestConst.b);
Console.ReadLine();
}
}

We cant access a const variable through object of class. We can always access a const variable with class name only.
Like : ClassName.ConstVariableName

No comments:

Post a Comment