English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed explanation of the usage of const and readonly modifiers in C#

1. Only C# built-in types (int, double, long, etc.) can be declared as const; results, classes, and arrays cannot be declared as const.

2. readonly is a modifier used on fields, accessed directly as class.name

3. const must be initialized in the declaration. It cannot be modified after that.

4. readonly can be initialized in the declaration or in the constructor, but cannot be modified in other cases.

namespace const_and_readonly

class Program

static void Main(string[] args)

Console.WriteLine("Half a year have {0} Moths", Calendar.Moths/2); //Direct class name field access to const fields
Calendar test1 = new Calendar();
Console.WriteLine("Every year has {0} weeks and {1}1._weeks, test1._days);//readonly fields can be accessed through instances
Calendar test2 = new Calendar(31, 4);
Console.WriteLine("January has {0} weeks and {1}2._weeks, test2 ._days);
Console.ReadKey();


class Calendar

public const int Moths = 12 //const must be initialized in the declaration
public readonly int _days=365 //readonly initialized in the declaration
public readonly int _weeks;
public Calendar() //readonly initialized in the constructor

_weeks = 52

public Calendar(int days, int weeks) //readonly initialized in the constructor

_days = days;
_weeks = weeks;

public void setvalue(int days, int weeks)

// _days = days; Cannot assign a value to a read-only field
//_weeks = weeks; Cannot assign a value to a read-only field

The above is the detailed explanation of the usage of const and readonly modifiers in C# introduced by the editor for everyone. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. At the same time, I would also like to express my heartfelt thanks to everyone for their support of the Yell Tutorial website!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.)

You May Also Like