Home >Backend Development >C#.Net Tutorial >What is the difference between the keywords const and readonly in C#?

What is the difference between the keywords const and readonly in C#?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-08-31 23:57:07770browse

C# 中关键字 const 和 readonly 有什么区别?

Constant

Constant fields are fields that cannot be modified. It needs to be assigned a value when declaring.

const int a = 5;

Readonly

​​>

Read-only fields are initialized when declared, or you can set it in the constructor.

Let's see an example where read only fields are only initialized inside the constructor -

Example

class Calculate {
   readonly int z;
   public Demo( ) {
      z = 20;
   }
}

The above is the detailed content of What is the difference between the keywords const and readonly in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete