Differences between readonly and const in ASP. NET, readonlyconst
Const is a keyword used to modify constants. It limits that a variable cannot be changed. Using const can improve the security and reliability of the program to a certain extent. It plays a very important role in programming and brings convenient applications to developers.
Create a console applicationTest:
Public class Test {public readonly string name = "George"; public const string coname = "ABC Company LLC"; public Test (string name) {// The variable modified by readonly can be changed only in Constructor (Constructor) this. name = name;} public string _ name {get {return name;} // you cannot perform the Set operation on the variable modified by readonly. // set // {// name = value; // }}} class Program {static void Main (string [] args) {Test obj = new Test ("Test"); // The value of the readonly variable cannot be modified, it can only be changed in Constructor (Constructor) // obj. name = "New Value"; Console. writeLine (obj. name); // The const variable is directly accessed through the object without instantiating the Console. writeLine (Test. coname); Console. read ();}}
I used to think that readonly and const serve the same purpose. Now I understand the differences between them. I wonder if you understand them too? Hope you will get something!