About Constants in C# with example

Good Morning..! Good Evening..! Good Afternoon..! at whatever time you are reading this article. In this blog post we will completely understand the use of constants in c# and we will also see the difference between use of constant keyword and readonly keyword using an example in c-sharp console applications.

What are Constants?

In oneliner defination - "Constants never change once declared in the lifetime of the program. They are absolute compile time constants".

Constant variables whose values never change for the life of the program. We can declare a value to a constant variable only once and then we can use that stored value throughout the execution of an application. Constants are similar to variable but only difference is the value once assigned to a constant cannot be changed. Constants are not strongly typed but you can declare constant values in a single place, permitting easy maintenance in an application. When we declare a constant value then that value is gets stored in the assembly metadata (IL code).

You can make code more readable by using meaningful constant names and the main benefit of using constants is that we can give a meaningful name to some "magic number", which improves code readability.

Constants cannot declared to methods, properties or events but they can be marked as public, protected internal, protected, internal or private. For more information on access modifiers click here.

Syntax of Constant in C#

 
 public const DataType constantName = value;

We have to use "const" keyword to declare constant variable.

Constants are effectively static because the value of the constant is the same in all instances of the class but you can declare constants without a static keyword an example is shown below.

 

    class clsPiValue
    {
        public const double Pi = 3.14;
    }
    class Program
    {
        
        static void Main(string[] args)
        {

            Console.WriteLine("PI Value is : " + clsPiValue.Pi);
                
        }
    }

Display Output :

PI Value is : 3.14.

As you see from above code that we have declared a constant variable "Pi" in a class "clsPiValue" and that constant value we are accessing in the console main program without an "clsPiValue" object. It means they are effectively static but without a static keyword.

Compile Time Error Test

In this we will test whether constants really give a compile time error, if we try to change constant value in the program. So to test that we have created a class called "clsTaxValue". Inside class we have created and declared the constant value then again in the constructor of a class we tried to change the constant value with a new value. The moment we tried to change the constant value with a new value we got the following error as shown below.

 

    class clsTaxValue
    {
        public const double TaxExemptionValue = 250000;

        public clsTaxValue(double ChangeofTaxValue)
        {
            TaxExemptionValue = ChangeofTaxValue;
        }
    }
    class Program
    {
        
        static void Main(string[] args)
        {
            
            Console.WriteLine("2014 Tax Value is : " + clsTaxValue.TaxExemptionValue);
                
        }
    }

Compile Time Error : The left-hand side of an assignment must be a variable, property or indexer.

Understand difference between constants and readonly using example

In this we will try to understand difference between constants and reeadonly.

Declaration of const constant

 
public const string ServerHost = "Google";

Declaration of readonly constant

 
public readonly string ServerUsername = "Sa";

In c# both of these guys are declared to achieve one common task i.e defining constants in the application.

Constants are declared using "const" keyword.

Readonly are declared using "readonly" keyword.

Let's take up a simple example to understand the differences.

 
class Program
{
        public const string ServerHost = "Google";
        public readonly string ServerUsername = "Sa";

        static void Main(string[] args)
        {
                
        }
}

As you see from above code that we have declared readonly variable and const variable. Now further what we will do that we will try to change both values in the main program scope.

 
class Program
{
        public const string ServerHost = "Google";
        public readonly string ServerUsername = "Sa";

        static void Main(string[] args)
        {
                ServerHost = "Yahoo"; //line 16
		    ServerUsername = "Foo"; // line 17
        }
}

After declaring both variables with new values with got the following compile time error as shown below.

Error

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

Line 17 : An object reference is required for the non-static field, method, or property 'ConstantExample.Program.ServerUsername'.

As you see from above that we cannot change the values of both "const" and "readonly" keyword variables. So now you must be thinking what's the difference why microsoft has provided the two different keywords to declare constants in the application.

Difference is there that's why microsoft visual studio has two different keywords to declare constants in projects.

Friends let me make you clear that :

"const" constants are = Compile Time Constants

"readonly" constants are = Run Time Constants.

Let me prove you that above statements using an example.

Constants are compile time constants

 

class Program
{
        public const string ServerHost;
        static void Main(string[] args)
        {
            ServerHost = "MSN";
           
        }

}

When we try to build the above program we got the following error message as shown below.

Error : A const field requires a value to be provided

So it means it is compulsory that we need to define some value to "const" keyword constant otherwise it will throw an error and as we seen in the above example that once the value is defined it will not change in any other parts of a program. So it is proved that "const" constants are compile time constants.

ReadOnly are Run Time Constants

 

class clsServerDetails
{
        public readonly string ServerPass;
}

When we build an application using above code we have not got any error the program ran successfully. So it means it is not compulsory to define a value during declaration of "readonly" constants. So it means we can set "readonly" constants value in run time also like as shown below.

 

    class clsServerDetails
    {
        public readonly string ServerPass;

        public clsServerDetails(string val)
        {
            ServerPass = val;
        }


         public clsServerDetails()
         {

             ServerPass = "Bar";
         }


    }


   class Program
   {
       
        static void Main(string[] args)
        {
            clsServerDetails obj = new clsServerDetails("Bar");
        }

   }


During runtime if the "readonly" constants are declared then as we seen in the above example that once the value is defined it will not change in any other parts of a program.

So it is proved that "ReadOnly" Constants are Runtime constants.

So use "const" constants if you want to create absolute constants and use "readonly" constants if you just want to create a constant during run time in a program.

Const Keyword Constants are stored in IL Code

Let me prove that const keyword constants or compile time constants are saved in IL code and run time constants are not stored in IL code.

Let's take up simple example.

 

class Program
{
        public const int BaseStart = 99;
        public readonly int EndAt = 999;
        static void Main(string[] args)
        {
           
        }

}

Now build this program and go to microsoft visual studio tools -> Visual studio command prompt. Inside the command prompt type "ILDASM" and press "ENTER". ILDASM tool will open up then go to top menu file -> open -> open exe file of the above program.

As you see from above images that compile time constants are baked in the IL code value is shown below.

.field public static literal int32 BaseStart = int32(0x00000063).

So hope you understood the differences between "const" keyword and "readonly" keyword. See also difference between enums and constants.

So hey friends this is all about understanding step by step about constants in c-sharp and also understanding differences between const and readonly keyword. If you like this article and found helpful then kindly click on share button to share this article in your social media channels. If you have any doubts kindly post your queries in the comment section below...Thanks you...!

Author: Gurunatha Dogi

Gurunatha Dogi

Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more

Comments

64x64
By Gaurav tyagi on 2014-08-16
thanks , it may lot of helpful to me. keep posting

Add a Comment