Learn C#.NET, ASP.NET MVC 5,ASP.NET Core that you can increase your knowledge and coding to develop the real-time project.

Sunday, May 27, 2018

Constant Vs Readonly In C#

Difference between constant and readonly in C#
difference between variable and constant in c#

1. constant:
  •  It is used to store the constant value.
  •  It is compiled time constant.
  •  We can not modify/change the constant value.
  •  The Constant variable can by access by using the class name.
  •  We must assign the value to the constant variable at the declaration time.
  •  We can not provide the static keyword to the constant variable.
  •  We can not access the constant variable by using object of the class.

2. Readonly keyword:
  •  It is used to store the constant value.
  •  It is run time constant.
  •  We can modify/change the readonly variable value in the constructor of the class.
  •  The readonly variable can be accessed by using object of the class or class name.
  •  we can provide the static keyword to the readonly variable.
  •  We can access the readonly variable by using object of the class or class name.


using System;
namespace CSharpProject
    class Program
        public const string strConnection = "Test Connection";
        //public static readonly double Pi = 3.1; // we can define static keyword to the readonly variables
        public  readonly double Pi = 3.1;
        public Program()
            Pi = 3.14;
        static void Main(string[] args)
            Program pro = new Program();
            Console.WriteLine(pro.Pi); // Calling not static readonly variable by using object of class.
           // Console.WriteLine(Program.Pi);// calling static readonly keyword by using class name.

More Details watch the following video on the same:



Post a Comment

Upcoming Articles/Videos

Design Pattern
SOLID Design Principles
Copyright © Programming With Shri | Powered by Shrimant Telgave Home | Disclaimer | Privacy Policy | Terms and Conditions Design by Shrimant Telgave