The difference between const and readonly in C#.net

Source: Internet
Author: User
(1) Both readonly and Const are used to indicate constants.
(2) initialization assignment is different.
Const-Modified constants must be assigned values at the same time as the declaration. For example:





public class Class1
{
     public const int MaxValue = 10; // declared correctly
     public const MInValue; // Error: constant field requires a value
     public Class1 ()
     {
         MinValue = 10;
     }
}


The readonly field can be assigned in the process of initializing (declaring or constructing a function). Therefore, depending on the constructor used, the ReadOnly field may have different values.



public class Class1
{
     public readonly int c = 10; // declared correctly
     public readonly int z;
     public Class1 ()
     {
         z = 24; // correct
     }
     protected void Load ()
     {
         z = 24; // Error: Cannot assign a value to a read-only field (except in the constructor or variable initial value specified)
     }
}


ReadOnly are instance members, so different instances can have different constant values, which is readonly more flexible.




public readonly Color Red = new Color(255, 0, 0);  
public readonly Color Green = new Color(0, 255, 0);  
public readonly Color Blue = new Color(0, 0, 255);


(3) The Const field is a compile-time constant, and the ReadOnly field can be used to run a constant number.
Const requires the compiler to be able to calculate a definite value at compile time. At compile time, use the computed value to replace every place where the constant is called. Therefore, you cannot extract a value from a variable to initialize the constant.
ReadOnly allows you to set a field to a constant, but you can perform some operations to determine its initial value. Because ReadOnly is executed at the time of calculation, some variables can be initialized. This value is determined at run time.
(4) The const default is static, and readonly must display a declaration if it is set to static.
(5) The type of the const-modified value is also limited, and it can only be one of the following types (or can be converted to the following types): SByte, Byte, short, ushort, int, uint, long, ulong, char, float, double, Decimal, bool, string, enum type, or reference type. Note reference types that can be declared as const can only be string or other reference types with a value of NULL. ReadOnly can be of any type.
That is to say, when we need a const constant, if his type restricts it from being compiled to a definite value, then we can take it as a static readonly. But there is a slight difference between the two. Look at the following two different files.
File1.cs




using System;  
namespace MyNamespace1  
{  
    public class MyClass1  
    {  
        public static readonly int myField = 10;  
    }  
}



File2.cs




namespace MyNamespace2  
{  
    public class MyClass1  
    {  
        public static void Main()  
        {  
            Console.WriteLine(MyNamespace1.MyClass1.myField);  
        }  
    }  
}


Two classes belong to two files File1.cs and File2.cs, and compiled separately. When the domain MyField in file File1.cs is declared as static readonly, if we change the value of MyField to 20 for some reason, Then we just need to recompile the file File1.cs to File1.dll, which will get 20 when the File2.exe is executed.
However, if you change the static readonly to const and then change the initialization value of the MyField, We would have to recompile all the files referenced to File1.dll, otherwise the MyNamespace1.MyClass1.myField we quoted would not change as we wished. This is especially important in the large system development process.
(6) object, array (array), and struct (struct) cannot be declared as const constants.



The above is the c#.net in the const and readonly the difference between the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

Related Article

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.