C# Coding Standards – Use the const Directive Only on Natural Constants

ccoding-standards

I've seen these 2 guidelines in coding c# standard and I’m not sure the what the 2nd one means.

  1. With the exception of zero and one, never hard-code a numeric value; always declare a constant instead.
  2. Use the const directive only on natural constants such as the number of days of the week.

What is the definition of a natural constants and if the number is not a natural constants given the 1st rule how does one declare a constant in c# without the const directive?

So how is the 2nd rule not contradicting the 1st rule for non natural constants?

See http://www.scribd.com/doc/10731655/IDesign-C-Coding-Standard-232 for reference.

Best Answer

You cannot declare a "constant" without the const directive. When it refers to "natural constants" it's simply referring to values which are defined by an immovably obvious guarantee, something that is axiomatic, for example:

There are 7 days in a week. This will never change.

There are 12 inches in a foot. This will never change.

These seem pretty fixed and hard to identify relatably to a real situation though, there are however fixed guarantees similar to this which you can find in your own systems surely.

For example, say you're writing a web service, and you are versioning the contracts as you should, so you have an OblogonRepository service, it would be reasonable to claim inside that service:

This is version 1 of the OblogonRepository. This will never change.


Now that all of that has been said, let me go on to say, this rule sounds very restrictive and I don't particularly agree with it.

It is however very important to understand the behaviour of a const in C#, in relation to this: Everywhere a const is referenced, it will at compile time be replaced by a fixed reference to the literals in the assemblies table. This means if you have other assemblies referencing this const, and you compile them then recompile the assembly with the const with changed values, the referencing assemblies will not have the const value updated until you recompile them.

Do be cautious with consts, but in my personal subjective opinion, this rule is far more restrictive than is useful. Using consts for things like max allowed users or column numbers is completely common idiomatic C#, even though they may change unlike "natural numbers".

Here's a little further reading on consts which details their compile time behaviour: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/01/c-fundamentals---what-is-the-difference-between-const-and.aspx

This article claims a rule which sounds pretty spot on to me (emphasis mine):

Thus, const should be used mainly for values that are not subject to change, or [can be used] freely if the scope of the const is limited to the same assembly or smaller.