Tuesday, May 28, 2013

Constants

As the name suggests Constants are a type of class members whose value is defined at the time of writing the program and remain constant forever, the values of constants cannot be changed at runtime, the values of a constant defined in a class will remain same for every instance that is created from the class.

Constants are declared using the
const keyword as follows.
    const int nId = 25;
    const string sName = "Name1";

If we try to assign a value to a constant at runtime the compiler will throw the following error.

The left-hand side of an assignment must be a variable, property or indexer

Only pre-defined types like int, string etc can be declared as constants, we cannot declare custom types like class, structs etc as constants.

Constants which are decared with a public scope can be assessed from outside the class like static members, even though we don’t add a static keyword while defining the constant. This makes sense because the value of the constant is not going to changes irrespective of how many every instance created from the class.

In the following example we will define 2 constants.
    class CEmployee
    {
        public const int nId = 25;
        public const string sName = "Name1";
    }

The above constants can be accessed outside the class as follows.

    Console.WriteLine(CEmployee.nId);
    Console.WriteLine(CEmployee.sName);

The above line will get executed without any errors and will print the value of the constants declared in the CEmployee class. 

Search Flipkart Products:
Flipkart.com

No comments: