How to use readonly variable
How can we assign value to readonly variable in C#?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Hermes Condez37 reputationPosted Feb 29, 2012, 9:13 PM EST
http://stackoverflow.com/questions/6848441/assign-value-of-readonly-variable-in-private-method-called-only-by-constructors
Jignesh TrivediRank #16 · 50.3K reputationPosted Feb 29, 2012, 9:49 PM EST
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.