Friday, July 16, 2004

VJs Tip Of The Day - July 16th 2004

Const vs readonly in C#

const (Constants) are variables whose values are set at compile time, either by the programmer or by the compiler... It cannot be modified there after, so if you need a field whose value is known at compile time and should not be changed anytime later then you should declare that field as const... Intersting note is that const fields are statis by default and so you do not need to instantiate a class to access them...

readonly (Read Only) are variables whose values are set at run time, but only once... The value of such variables are set in the constructors and cannot be modified there on... These variables are useful when you want the value of the variable to be fixed but fixed to a value which is known only at run time...

Now if you need a static variable whose value is known only at runtime then make it static readonly... :-) 

Sudhir from TCS wanted to add the tip above below is his note:
Hi Vishal    a little addition in yr Tip What is the difference between CONST and READONLY? Both are meant for constant values. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. readonly int b; public X() { b=1; } public X(string s) { b=5; } public X(string s, int i) { b=i; } Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

No comments: