Last post Jun 23, 2008 11:39 AM by aartimalik19
Mar 31, 2008 03:28 AM|satya_chhikara|LINK
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.
readonly int MaxDocuments;
public static 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.
MaxDocuments = 20; //Dosomething();
Jun 23, 2008 11:39 AM|aartimalik19|LINK
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.