Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

20 June 2012

Constant member in C#


“Constants are values which are known at compile time and do not change at runtime”

Constant declared as field member in the class and must be initialized after declaration. Constant is declared using const keyword before data type of the field.
Syntax:
public const [data type] [field name]= value;

Example:
public const int weekdays = 7; //Declaration and Initialization of single const value
public const int weekdays = 7, yeardays = 365, monthdays = 30; //Declaration and Initialization of multiple const value of same datatype
const double monthweeks = monthdays  / weekdays ; //value as expression
Example:
class ConstantMember
    {
        public const double pi = 3.14;
        public const string strRefType = null//Nullable ref type        
        public const WeekDays enumConstant = WeekDays.Monday;
        public static void Main()
        {
            //pi = 4.15; // Compile Error as The left-hand side of an assignment must be variable, property or indexer.
            Console.WriteLine("/*********** Constatnt member Example **********/");
            Console.WriteLine("Global Constant Pi value is {0}", pi); //Global constant
            const double root2 = 1.414; //local constant
            //root2 = 2; // Compile Error
            Console.WriteLine("local Constant root2 value is {0}", root2);
            Console.WriteLine("Constant from Enum. Enum value is {0}", enumConstant);
            Console.WriteLine("Constant from ref type. Enum value is {0}", strRefType);
            Console.Read();
        }
    }
    enum WeekDays
    {
        Monday = 1,
        Tuesday = 2
    }
Output:


Data points:
  • Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.
  • Constants can use any of access modifiers.
  • If you try to reassign the constant value in the code then we will get compile time error as “The left-hand side of an assignment must be variable, property or indexer.
  • If you want to change the value of constant at run time the use read-only members.
Constant with static keyword:
Constants cannot be marked with static keyword.
public static const  double pi = 3.14; // Compile Error as ‘pi’ cannot be marked as static

In case of readonly we can use static keyword.
public static readonly double pi = 3.14; // correct

Advantage:
Updating single constant value will affect the entire calculations of your program.
E.g; You have Service Tax as constant in your project. Today it might be 4% if in future it changes to 5% then updating single constant value will affect your entire calculations of the program.

0 Comments:

Post a Comment