What is the Difference between read only and constant
variables?

Answer Posted / sandya

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
public const int X = 10;
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.

class MyClass
{
readonly int X = 10; // initialized at the time of declaration
readonly int X1;
}

public MyClass(int x1)
{
X1 = x1; // initialized at run time
}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the difference between read and readline in c#?

713


Explain the accessibility modifier protected internal?

645


What is difference between a type and class?

802


What is difference between a function and a method?

685


Write the syntax for catching an exception in c#?

655


Explain how obfuscator works in .net

747


Define an assembly in .net?

736


What is difference between class and abstract class in c#?

652


How many constructor can a class have?

698


How do I declare a pure virtual function in c#?

746


What is the difference between virtual and override in c#?

727


Why cannot you specify the accessibility modifier for methods inside the interface?

676


What are the benefits of using generics in c#?

670


What is ioc containers c#?

653


Why is xml called extensible?

662