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
What are PE(Portable Executable)?
What is msil, and why should developers need an appreciation of it if at all?
What is callback method in c#?
What is the difference between firstordefault and first?
1. Describe page life cycle?
What is the use of functional interface?
What is autopostback in c#?
What is a multicast c# delegate?
How do destructors and garbage collection work in c#?
What is base class in c#?
What is the c# equivalent of c++ catch (…), which was a catch-all statement for any possible exception? Does c# support try-catch-finally blocks?
What is difference between first and firstordefault?
Is static thread safe?
How does the lifecycle of Windows services differ from Standard EXE?
Is inheritance possible in c sharp?