Home Backend Development C#.Net Tutorial The difference between const and readonly in c#.net

The difference between const and readonly in c#.net

Jan 19, 2017 am 11:07 AM

(1) readonly and const are both used to mark constants.
(2) The initialization assignment is different.
const-modified constants must be assigned a value at the same time they are declared. For example:

public class Class1  
{  
    public const int MaxValue = 10;       //正确声明  
    public const MInValue;                   //错误:常量字段要求提供一个值  
    public Class1()  
    {  
        MinValue = 10;  
    }  
}
Copy after login

readonly fields can be assigned during initialization (declaration or constructor). Therefore, readonly fields may have different values ​​depending on the constructor used.

public class Class1  
{  
    public readonly int c = 10;           //正确声明  
    public readonly int z;  
    public Class1()  
    {  
        z = 24;//正确  
    }  
    protected void Load()  
    {  
        z = 24;//错误:无法对只读的字段赋值(构造函数或变量初始值指定项中除外)  
    }  
}
Copy after login

readonly is an instance member, so different instances can have different constant values, which makes 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);
Copy after login

(3) const fields are compile-time constants, while readonly fields can be used for run-time constants.
const requires the compiler to be able to calculate a certain value at compile time. At compile time, every place where the constant is called is replaced with the calculated value. Therefore you cannot extract a value from a variable to initialize a constant.
readonly allows a field to be set to a constant, but some operations can be performed and its initial value can be determined. Because readonly is executed at calculation time, it can be initialized with certain variables. This value is determined at runtime.
(4) const is static by default, and readonly must be explicitly declared if it is set to static.
(5) The type of value modified by const is also limited. 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 that the reference type that can be declared as const can only be string or other reference types whose value is null. readonly can be of any type.
That is to say, when we need a const constant, if its type restricts it from being calculated to a definite value during compilation, then we can solve it by declaring it as static readonly. But there is still a slight difference between the two. Look at the two different documents below.
file1.cs

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


file2.cs

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

The two classes belong to two files file1.cs and file2.cs and are compiled separately. When the domain myField in the file file1.cs is declared as static readonly, if we change the value of myField to 20 due to some need, then we only need to recompile the file file1.cs to file1.dll. When executing file2.exe That is, you will get 20.
But if you change static readonly to const and then change the initialization value of myField, we must recompile all files that reference file1.dll, otherwise the MyNamespace1.MyClass1.myField we reference will not be as we expected. Willing to change. This is especially important to pay attention to during the development of large systems.
(6) object, Array (array) and struct (structure) cannot be declared as const constants.

The above is the difference between const and readonly in c#.net. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
What is the readonly feature and how to use the function in Vue3 What is the readonly feature and how to use the function in Vue3 May 10, 2023 pm 10:04 PM

Detailed explanation of the readonly feature in Vue3 readonly is a new feature provided in Vue3, which is used to turn a responsive object into a read-only object. Using readonly can ensure that an object can only be read and cannot be modified, thus improving the stability and security of the application. In Vue3, you can use the readonly function to convert an object to a read-only object, for example: import{readonly}from'vue'conststate=readonly({count:0}) In the above code, the state object is converted to read-only object, which means state.count

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Deep understanding of const in C language Deep understanding of const in C language Feb 18, 2024 pm 12:56 PM

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint

C++ syntax error: const objects must be initialized when defined, how to deal with it? C++ syntax error: const objects must be initialized when defined, how to deal with it? Aug 22, 2023 am 09:13 AM

For C++ programmers, syntax errors are one of the most common problems. One of the common mistakes is that const objects must be initialized at definition time. If you encounter this situation, how should you deal with it? First, we need to understand what a const object is. The const keyword is a special type qualifier in C++ that specifies that the value of a variable cannot be changed during the execution of the program. Such variables are called "constants". If you define a const object without initializing it, you will encounter the above error. This is

18 Ways to Fix Audio Service Not Responding Issue on Windows 11 18 Ways to Fix Audio Service Not Responding Issue on Windows 11 Jun 05, 2023 pm 10:23 PM

Audio output and input require specific drivers and services to work as expected on Windows 11. These sometimes end up running into errors in the background, causing audio issues like no audio output, missing audio devices, distorted audio, etc. How to Fix Audio Service Not Responding on Windows 11 We recommend you to start with the fixes mentioned below and work your way through the list until you manage to resolve your issue. The audio service may become unresponsive for a number of reasons on Windows 11. This list will help you verify and fix most issues that prevent audio services from responding on Windows 11. Please follow the relevant sections below to help you through the process. Method 1: Restart the audio service. You may encounter

What are the correct uses of the const keyword in C++ functions? What are the correct uses of the const keyword in C++ functions? Apr 11, 2024 pm 02:36 PM

Correct usage of the const keyword in C++: Using const to modify a function means that the function will not modify the parameters or class members passed in. Using const to declare a function pointer means that the pointer points to a constant function.

How to use const in c language How to use const in c language Sep 20, 2023 pm 01:34 PM

const is a keyword that can be used to declare constants, const modifiers in function parameters, const modified function return values, and const modified pointers. Detailed introduction: 1. Declare constants. The const keyword can be used to declare constants. The value of the constant cannot be modified during the running of the program. The constant can be a basic data type, such as integer, floating point number, character, etc., or a custom data type; 2. The const modifier in the function parameters. The const keyword can be used in the parameters of the function, indicating that the parameter cannot be modified inside the function, etc.

See all articles