Asp. NET in readonly and const difference Detailed _ Practical skills

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.