namespace GroupConsole
{
public class TestClass
{
//This statement will excute even before first instance is
created.
//So assigning a value to readonly is perfectly fine.
public static readonly int data1 = ReturnData();
// public static readonly int data2 = AssignData(); //Error
public static readonly int data2;
private static int ReturnData()
{
return 10;
}
private static void AssignData()
{
data2 = 100; // This can not be done.
// Because method can be called at any point of code.
Changing readonly value is not allowed.
}
static TestClass()
{
data2 = 50; // Perfectly fine.
//readonly values are has to be initialized in constructor.
There is no other place to initialize them.
// because data is static constructor has to be static....
because constructor is static, can not accept arguments.
}
}
class Program
{
static void Main(string[] args)
{
TestClass testobject = new TestClass();
Console.WriteLine(TestClass.data1.ToString());
Console.WriteLine(TestClass.data2.ToString());
Console.ReadLine();
}
}
}
readonly is useful when a constant needs to be initialized by client of
the class. For this the class constructor accepts a parameter and
assigns to readonly. From that point onwards readonly will behave like
a constant.
by qualifyinh a readonly data with static, you can only initialize the
data in a static constructor, which will not accept any parameters.
Meaning that client of the class can not assign the value at the object
initilization. class has to know the value by itself. which is as good
enough as a "const".
Finally.... static readonly data is nothing but const data.
replacing all the static readonly to const will make the code much
readable, because data will be assigned at the point of declaration....
not round a round way....
Hope I am clear what I want to say...
Thanks
-Srinivas.
sunil wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.
I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance