What is the difference between const and static readonly? (What is the difference between const and static readonly ?)

Source: Internet
Author: User

The essential difference is that the const value is determined during compilation, so it can only be specified through a constant expression during declaration. Static readonly calculates its value during running, so it can be assigned a value through a static constructor.

Let's see if the following statements can be exchanged:

 
1. static readonly testclass test1 = new testclass (); 2. static readonly testclass Test2 = NULL; 3. static readonly A = 20 * B; static readonly B = 2; 4. static readonly int [] array = new int [] {1, 2, 3, 4, 5}; 5. void test () {const int c = 1 ;...}

1: const cannot be changed. The new operator needs to execute the constructor and is determined during execution.

2: it can be changed to const, and the constant of the reference type can be null.

3: It can be changed to const. During the compilation, A = 40.

4: it cannot be changed to const, which is the same as 1.

5: it cannot be changed to readonly. readonly can only be used to modify the field of the class. It cannot modify local variables or other members such as property.

Therefore, static readonly can be used for those places that should be essentially constants but cannot be declared using Const.

Let's look at the following example:

Class program {public static readonly test = new test (); static void main (string [] ARGs) {test. name = "program"; // OK test = new test (); // error :}} class test {public string name ;}

 

Static readonly requires note that for a reference type of static readonly, the value assignment (write) operation is not allowed. The read and write operations on its members are still unrestricted.

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.