Thursday, July 22, 2004

 

Const vs. Readonly in C#








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...
Interesting note is that const fields are static 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... See this is what C# offers... :-)

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


Mitesh Mehta



Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?