Detailed explanation of the difference between readonly and const in ASP. NET
- 2021-07-02 23:56:24
- OfStack
const is a keyword that modifies a constant and qualifies that a variable is not allowed to be changed. Using const can improve the security and reliability of programs to a certain extent. It plays a very important role in program design and brings very convenient applications to developers.
Let's build a console application for testing:
public class Test
{
public readonly string name = "George";
public const string coname = "ABC Company LLC";
public Test(string name)
{
// readonly Modified variables can and can only be used in Constructor (Constructor) is changed in
this.name = name;
}
public string _name
{
get
{
return name;
}
// You can't be right readonly Modified variables are carried out Set Operation
//set
//{
// name = value;
//}
}
}
class Program
{
static void Main(string[] args)
{
Test obj = new Test("Test");
//readonly You can't modify the value of the variable, only in the Constructor (Constructor) is changed in
//obj.name = "New Value";
Console.WriteLine(obj.name);
//const The variables of are accessed directly through objects without instantiation
Console.WriteLine(Test.coname);
Console.Read();
}
}
Previously, I thought that readonly and const had the same function. Now I understand the difference between them. I don't know if you also understand it. I hope everyone has gained something!