locked
Difference between ReadOnly and Constant field. RRS feed

  • Question

  • User1750785767 posted

     

    Difference between ReadOnly and Constant field.

    The concept of a constant, as a variable that contains a value that can’t be changed is something that C# shares with most programming language. On occasion, you may have some variable whose value should not be changed, but where the value is not known until runtime. The ReadOnly keyword gives a bit more flexibility than Constant, allowing for the case in which you might want a field to be constant but need to carry out some calculations to determine its initial value. The rule is that you can assign values to ReadOnly field inside a constructor, but not anywhere else. It’s also possible for a ReadOnly field to be an instance rather than a static field having different value for each instance of a class. This means that, unlike a constant field, if you want a ReadOnly field to be static, you have to declare it as such.

    public class DocumentEditor<o:p></o:p>

    {<o:p></o:p>

        public static readonly int MaxDocuments;<o:p></o:p>

    <o:p> </o:p>

        public static DocumentEditor()<o:p></o:p>

        {<o:p></o:p>

            MaxDocuments = 100; //Dosomething();<o:p></o:p>

        }<o:p></o:p>

    }<o:p></o:p>

      The field is static, since the maximum number of documents only needs to be stored once per running instance of the program.

    public class DocumentEditor<o:p></o:p>

    {<o:p></o:p>

        public readonly int MaxDocuments;<o:p></o:p>

    <o:p> </o:p>

        public DocumentEditor()<o:p></o:p>

        {<o:p></o:p>

            MaxDocuments = 20; //Dosomething();<o:p></o:p>

        }<o:p></o:p>

    }

     

    Monday, March 31, 2008 3:28 AM

All replies

  • User-87683385 posted

     Initailization of constant variable done at the time of declaration it is a compile time constant where as read only variable can be used as a run time constant by initialize at the time of declaration as well as in costructor.

    Monday, June 23, 2008 11:39 AM