7/26/2010

C# Constants


Constants:
----------
A value which does not change during the execution of a program is known as constant.
Constants are used in a situations, the value is known when we write a program.
A constant can be based on another constant, but it does no based on value of a variable or a method.
Example:
         const int x=5;    //valid declaration
         const int y=x+3;  //valid declaration

         int y=6;        //valid declaration
         const int x=y+7; //Invalid declaration

At compile time the compiler replaces the occurrence of each constant with a literal value. 
Constants are static by default.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication19
{
    class values
    {
     public   const int x = 4;
      public  const int y = x + 3;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Sum: " + (values.x + values.y));
        }
    }
}


No comments:

Post a Comment