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#?

WBOY
Release: 2023-08-31 23:57:07
forward
736 people have browsed it

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;
Copy after login

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;
   }
}
Copy after login

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!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template