Set Read-Only variables that can be initialized in. NET

Source: Internet
Author: User

In. in net, the const keyword is usually used to declare constants, but sometimes some constants are read from a configuration file or database. once read, they are no longer changed, what should we do at this time? In fact, it is very simple to use static constructors of classes.

When using this static constructor, add the readonly keyword to the variable so that the variable can be a read-only attribute after initialization, and others can no longer change it. The Code is as follows.

Public class Class1
...{
Public static readonly string s = "1 ";

Static Class1 ()
...{
S = "3 ";
}
}

The code for reading constant S is as follows:

Class Program
...{

Static void Main (string [] args)
...{

Console. writeline (class1.s );
}

}

At this time, we will find that the value 3 is printed on the screen, that is, the constant is already set in the static constructor, And it is read-only and cannot be changed. Note that the static constructor does not have the modifier such as public. If the modifier is added, the compilation fails.

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.