What is the difference between const
and readonly
in C#?
When would you use one over the other?
Here's another link demonstrating how const isn't version safe, or relevant for reference types.
Summary:
They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.
Example:
public static class Text {
public const string ConstDescription = "This can be used.";
public readonly static string ReadonlyDescription = "Cannot be used.";
}
public class Foo
{
[Description(Text.ConstDescription)]
public int BarThatBuilds {
{ get; set; }
}
[Description(Text.ReadOnlyDescription)]
public int BarThatDoesNotBuild {
{ get; set; }
}
}
Another gotcha.
Since const really only works with basic data types, if you want to work with a class, you may feel "forced" to use ReadOnly. However, beware of the trap! ReadOnly means that you can not replace the object with another object (you can't make it refer to another object). But any process that has a reference to the object is free to modify the values inside the object!
So don't be confused into thinking that ReadOnly implies a user can't change things. There is no simple syntax in C# to prevent an instantiation of a class from having its internal values changed (as far as I know).
const
: Can't be changed anywhere.
readonly
: This value can only be changed in the constructor. Can't be changed in normal functions.
I believe a const
value is the same for all objects (and must be initialized with a literal expression), whereas readonly
can be different for each instantiation...
A const
has to be hard-coded, where as readonly
can be set in the constructor of the class.