Breaking News

Editors Picks

Tuesday, June 21, 2011

const keyword in c sharp

const C# 
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified. For example:

const int s = 0;
public const double gravitationalConstant = 9.673e-11;
private const string productName = "Visual C#";
The static modifier is not allowed in a constant declaration.
A constant can participate in a constant expression, as follows:

public const int c1 = 5;
public const int c2 = c1 + 100;

The readonly keyword differs from the const 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. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants,

Example
public class ConstTest 
{
    class SampleClass 
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;
        public SampleClass(int p1, int p2) 
        {
            x = p1; 
            y = p2;
        }
    }
    static void Main() 
    {
        SampleClass mC = new SampleClass(11, 22); 
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}", SampleClass.c1, SampleClass.c2 );
    }
}
/* Output
    x = 11, y = 22
    c1 = 5, c2 = 10
 */

No comments :

Post a Comment

Contact Us

Name

Email *

Message *