Possible Duplicate:
What is the difference between const and readonly?
i have doubt in c# what is difference in constant and readonly explain with simple problem or any reference.
Possible Duplicate:
What is the difference between const and readonly?
i have doubt in c# what is difference in constant and readonly explain with simple problem or any reference.
A const
is initialized at compile time, and cannot be changed.
A readonly
is initialized at runtime, but can be done only one time (in the constructor, or inline declaration).
const
is a compile-time constant: the value you give is interpolated into your code as it's compiled. This means that you can only have constant values of types that the compiler understands, for example integers and strings. Unlike readonly, you couldn't assign the result of a function to a const field, for example:
class Foo {
int makeSix() { return 2 * 3; }
const int const_six = makeSix(); // <--- does not compile: not initialised to a constant
readonly int readonly_six = makeSix(); // compiles fine
}
A readonly
field, on the other hand, is initialised at runtime, and can have any type and value. The readonly
tag simply means that the field can never be re-assigned once it's been set.
Beware, though: a readonly collection or object field can still have its contents changed, just not the identity of the collection that's set. This is perfectly valid:
class Foo {
readonly List<string> canStillAddStrings = new List<string>();
void AddString(string toAdd) {
canStillAddStrings.Add(toAdd);
}
}
but we would not be able to replace the reference in this case:
class Foo {
readonly List<string> canStillAddStrings = new List<string>();
void SetStrings(List<string> newList) {
canStillAddStrings = newList; // <--- does not compile, assignment to readonly field
}
}
Constants (const
) must be known at compile time.
readonly
fields can be initialized (and only initialized) with a value known at run time.
A const
can never change, the declared value is burnt into the code at compile-time.
A readonly
field is initialised at runtime, but can only be initialised either in the object's constructor or in the field declaration itself.
Since const values are evaluated at compilation time if you use a const in assembly1 defined in assembly2 you would need to compile again assembly1 in case that the value of the const changes. This doesn't happen with readonly fields since the evaluarion is on runtime.
constast are initialized at runtime and can be used as static members. readonly can be intialized at runtime and only once.
In c#, constant members must be assigned values at compile time. But you can initialize once readonly members in run time.