While i was checking thru the exam question in dotnetspider i came across a question on readOnly variable,so i found it interesting and tested the Difference between 'ReadOnly' Field and 'Const' .
here are they
1.initialization of a Const member values are done at the declaration of the member whereas Readonly can be initialized at the declaration as well as in a constructor. class Test { private const int i=10 ; //constant initialization private readonly int k=12; //readOnly initialization Test(int Kchange ) { k=k+Kchange; //readOnly initialization in constructor } } 2.Const members is a compile-time constant whereas readonly fields can be used as runtime constant (value assigned only at runtime ) class Test { private readonly uint tm; Test() { tm=(uint)DateTime.Now.Second ; //readOnly initialization at runtime } }
--------------------------------------------------------------------------------------------------------- To understand and test yourself ,the entire code and OUTPUT is here
class Test {
private const int i=10 ; //constant initialization private readonly int k=12; //readOnly initialization private readonly uint tm; private int j;
Test() { j=12; tm=(uint)DateTime.Now.Second ; //readOnly initialization at runtime }
Test(int Kchange ) { k=k+Kchange; //readOnly initialization in constructor }
static void Main(string[] args) { Class1 c1=new Class1 (); Class1 c2=new Class1 (5); //calls constructor2 and add 5 to readonly variable 'K' c1.j=100;
Console.WriteLine("constant value is {0}",i); Console.WriteLine("Class member value is {0}",c1.j); Console.WriteLine("ReadOnly as constant value is {0}",c1.k); Console.WriteLine("ReadOnly when initialized in constructor is {0}",c2.k); Console.WriteLine("ReadOnly as runtime constant {0}",c1.tm);
} }
OUTPUT
constant value is 10 Class member value is 100 ReadOnly as constant value is 12 ReadOnly when initialized in constructor is 17 ReadOnly as runtime constant 46
Hope it helps you Anil Rajan
|
| Author: Brainstorming Guy 27 Jan 2005 | Member Level: Diamond Points : 0 |
Hai, Good one
Regards, Brainstorming Guys
|
| Author: Litty Thomas 08 Feb 2008 | Member Level: Silver Points : 0 |
Your article covers most of the ponts. I am adding one more differences that isConstant variables can be assigned to the readonly. But readonly variables can’t be assigned to the constant variables.
|
| Author: Pradip 14 Nov 2008 | Member Level: Bronze Points : 1 |
Hey, one more difference is there. Const can only receive intinsic or enumerated type values, no class instance, object, structure variable or array.
On the other hand ReadOnly accepts all.
Regards, Pradip M
|
| Author: malaikani rajamani 30 Jan 2009 | Member Level: Bronze Points : 0 |
Fine nice one to know about
|