What is the basic difference between a "const" and "readonly" in C#?

 Posted by Akiii on 3/6/2012 | Category: C# Interview questions | Views: 4451 | Points: 40
Answer:

const = const variables are implicitly static and they must be defined when declared. Example :-

private const  int testVariable = 500;


In the above code, a constant variable is declared and defined in the same time. If you don't initialize a const variable then it will results in compilation error.

readonly = The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

public readonly  int i = 5;


Example :-

class MyTestClass 

{
public readonly int i;

public MyTestClass()
{
i = 100; // Initialize a readonly instance field
}
}


In readonly , either you initialize in the declaration statement or you initialize it via a constructor.


I hope the above code samples are clear.

Thanks and Regards
Akiii


Source: MSDN | | Alert Moderator 

Comments or Responses

Login to post response