What is the difference between ReadOnly and Const?

 Posted by Tripati_tutu on 10/28/2010 | Category: ASP.NET Interview questions | Views: 7012 | Points: 40

ReadOnly: A ReadOnly field can be initialized either at the declaration time or in the constructor. The ReadOnly fields can have different values depending on the constructor used. The ReadOnly fields can be used for run time constants. It marks the field as unchangeable but the property can be changed inside the constructor of the class.

Const: A Const field can only be initialized at the declaration of the field. The Const fields can be used for compile time constants and it can’t change at run time. In a program where ever we are using Const, then that value will be replaced by the compiler.

Code Snippet:
namespace ClassLibrary

public class Test
public const int ConstValue = 10;
public static readonly int ReadonlyValue = 20;

By looking to the above code snippet, we can say ConstValue is declared as literal and it has an int value assigned to it whereas ReadonlyValue is declared as initonly and it has not been assigned any value to it.
So we can say that if a type is declared as Const, its value is known as compile time, but when the value that is declared as static readonly field, that cannot be known at compile time.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response