A const is a keyword that modifies a constant, restricting that a variable is not allowed to be changed. The use of const can improve the security and reliability of the program to some extent, it plays a very important role in the program design, and it is very convenient for the developers.
Here we build a console application for testing :
public class Test
{public
readonly string name = "George";
Public Const string Coname = "ABC company LLC";
The public Test (string name)
{
//readonly-decorated variable can and can only be changed in constructor (constructor)
this.name = name;
public string _name
{
get
{return
name;
}
You cannot set operations on readonly-decorated variables
//set
//{
// name = value;
class Program
{
static void Main (string[] args)
{
Test obj = new Test ("test ");
ReadOnly variables can not modify values and can only be changed in constructor (constructor)
//obj.name = "New value";
Console.WriteLine (obj.name);
The const variable is accessed directly through the object, and no instantiation of
Console.WriteLine (test.coname) is required;
Console.read ();
}
Previously thought that the role of ReadOnly and Const is the same, now understand the difference between them, do not know whether you also understand it? Hope you have some harvest!