Thursday, July 28, 2011

Use const and readonly in dotnet

Use const and readonly
When you need to specify fields that cannot be changed at runtime.

Both const and readonly are used to define data that does not change,
but there are important differences: const fields must be defined at declaration.
Because of this and the fact that they cannot change value, it implies that they
belong to the type as static fields. On the other hand, readonly fields can be set
at declaration or in the constructor, but nowhere else.

public class Vertex3d
private const string Name = “Vertex”;
private readonly int ver;

public Vertex3d()
ver = Config.MyVersionNumber;//Ok

public void SomeFunction()
ver = 13;//Error!

No comments:

Post a Comment