ReadOnly Vs Const Keyword

In C#, a const keyword is used to declare constant fields and constant local.
In C#, you can use a readonly keyword to declare a readonly variable

ReadOnly Keyword

1.In C#, readonly fields can be created using readonly keyword

2.ReadOnly is a runtime constant.

3.The value of readonly field can be changed.

4.It cannot be declared inside the method.

5.In readonly fields, we can assign values in declaration and in the constructor part.

6.It can be used with static modifiers.

// readonly variables

public readonly int myBike;
public readonly int myCar;

Const Keyword

1.In C#, constant fields are created using const keyword.

2.Const is a compile time constant.

3.The value of the const field can not be changed.

4.It can be declared inside the method.

5.In const fields, we can only assign values in declaration part.

6.It cannot be used with static modifiers.

// Constant fields

public const int myNumber= 10;
public const string str = "CsharpCode";

0 Comment's

Comment Form