Sunday, December 20, 2009

Difference between a constant and readonly variables/fields : (constant vs readonly)



Most of us would have encountered these questions

  • What is the difference between constant and readonly fields?
  • When to use constant and when to use readonly fields?
  • What is the advantage/disadvantage of each?

Constants
  • In C# you can declare a constant like this "const" is a keyword.
    public const string _constStrVar = "I am a static const str val";
  • A constant variable should have value at design time. 
  • All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".
  • Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls

Read Only 

  • Read only variables are created usually in the constructor of class. there fore it will have values before the constructor of the class exists
    class MyClass
    {
        public readonly string _strReadonly;
        public void MyClass(string strVal)
            {            _strReadonly = strVal;
              }       
            }


        a read only variable will have different values for each object whereas a constant variable will have only one.
        Post a Comment