How to use readonly variable
How can we assign value to readonly variable in C#?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Mar 1, 2012, 2:49 AM
You can assign a value to a readonly field in two way:
1) When the variable is initialized in the declaration
public readonly int Data1 = 25;
2) For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration.
public class Test
{
public readonly int Data1 = 25;
public readonly int Data2;
public Test()
{
Data2 = 24;
}
public Test(int arg1)
{
Data2 = arg1;
}
}
hope this help.
Hermes CondezPosted Mar 1, 2012, 2:13 AM
http://stackoverflow.com/questions/6848441/assign-value-of-readonly-variable-in-private-method-called-only-by-constructors