What is difference between readonly and const variable?

 Posted by Rajni.Shekhar on 4/9/2012 | Category: C# Interview questions | Views: 1810 | Points: 40

A const field can only be initialized only at declaration time of that field but readonly field can be initialized at the time of declaration or in constructor also. a const field will have only one constant value but readonly field can have different value depending on teh constructor.

Readonly is runtime ocnstant and cons field is compile time constant.


public class example{

public const int i = 20;

i=30;//compile time error.

public readonly int j=20;//initialized at declaration.

public readonly int l;

public example(){
l=30;//readonly field initialized in constructor also.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response