Groups > Asp .Net > ASP.NET Tips and tricks > Difference between ReadOnly and Constant field.




Difference between ReadOnly and Constant field.

Difference between ReadOnly and Constant field.
Mon, 31 Mar 2008 10:28:42 +000
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.

publicclassDocumentEditor

{

    publicstaticreadonlyint MaxDocuments;

 

    publicstatic DocumentEditor()

    {

        MaxDocuments = 100; //Dosomething();

    }

}

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

publicclassDocumentEditor

{

    publicreadonlyint MaxDocuments;

 

    public DocumentEditor()

    {

        MaxDocuments = 20; //Dosomething();

    }

}
Post Reply
about | contact