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


Const

Constant fields are the fields that cannot be modified. At the time of declaration, you need to assign a value to it.

const int a = 5;

Readonly

A Read-only field is initialized at the time of declaration or you can also set it within the constructor.

Let us see an example in which the read-only field is initialized inside the constructor −

Example

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements