Wednesday 21 August 2013

The readonly keyword in C# (and its similarity to adjectives)

This keyword, or more precisely a modifier, is that acts as a piece of in-code documentation. The readonly keyword says the member variable is initialized only on first declaration or in the constructor; nothing else can set the variable. It does not offer performance gains.

The const keyword on the other hand indicates a variable can only be initialized at the point of declaration. It is thus more restrictive than the readonly modifier.

Note that in-code documentation in the form of modifiers generally have to be verifiable by the compiler at compile time; this is one of the unwritten design rules of C#.

A modifier is anything used to modify the declaration of types and type members. An example modifier on a class is the partial modifier. Access modifiers comprise private, public, internal and protected.

Static is a modifier we hardly even think about; we use it so often in coding. Modifiers are like adjectives (e.g. the "blue" boat, the "static" void method).

No comments: