Readonly and const, readonlyconst
Readonly and const
In C #, both readonly and const define constants, but the difference is that readonly is the runtime constant, while const is the compilation constant.
public const int intValue = 100;public void Test(){ Console.WriteLine(intValue*100);}
In the above Code, intValue is a constant of the int type and is initialized with 100, that is, intValue is 100. The compiler will replace the intValue in the program with 100 during compilation.
class Test{ public readonly Object _readOnly; public Test() { _readOnly=new Object(); //right } public void ChangeObject() { _readOnly=new Object(); //compliler error }}
Use readonly to mark the _ readOnly variable as a read-only (constant). This indicates that the variable is a constant, rather than the object it points to is a constant (see the following code ). In addition, unlike const, the bound object has been determined during compilation, which is dynamically implemented at runtime according to requirements, as shown in the code above, _ readOnly is initialized in the constructor. You can specify different initial values for _ readOnly through the constructor. Once this value is specified, it cannot be changed during running.
class Person{ public int Age{get;set;}}class Test{ private readonly Person _readOnly; private readonly int _intValue; public Test() { _readOnly=new Person(); _intValue=100; } public Test(int age,int value) { _readOnly=new Person(){ Age=age;} _intValue=value; } public void ChangeAge(int age) { _readOnly.Age=age; } public void ChangeValue(int value) { _intValue=value; //comppiler error } public int GetAge() { return _readOnly.Age; } public int GetValue() { return _intValue; } public static void Main() { Test testOne=new Test(); Test testTwo=new Test(10,10); Console.WriteLine("testOne: "+testOne.GetAge()+" "+testOne.GetValue()); Console.WriteLine("testTwo: "+testTwo.GetAge()+" "+testTwo.GetValue()); testOne.ChangeAge(20); testTwo.ChangeValue(20); Console.WriteLine(testOne.GetAge()); Console.WriteLine(testTwo.GetValue()); }}
The biggest difference between readonly and const is that readonly is bound at runtime and can define object constants, while const can only define constants of value types (such as int.