Defining Constant Class Data in C#

This post is based on Chapter 5 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

The const keyword

So sometimes you might want to define some point of data for your application that is never to be changed. To this end we have the const keyword. Members defined with this keyword are implicitly static and can be accessed at the class level.

So why not just have a static property with only a get accessor I hear you think… well, another trait of the const keyword is that the value must be set at the point of defining the const variable. So this in effect means that you will only be able to set this variable once, in one specific place.
Also understand that the value of a const variable must be known at compile time (which is why you must set the value when defining this) – so you cannot for example set this to a config value or a database value. When .NET says this is constant – it really means it!

As opposed to this a static property will always rely on a private member that could potentially be redefined elsewhere. There is nothing wrong with that approach, but coding can be a complicated process and keywords like const are here to help you simplify the task by allowing you to built your intention into the code, if that makes sense?

The obvious example is perhaps PI – say you needed to define this somewhere – you would not want anyone subsequently modifying the value later on in you class somewhere – you know this is a globally valid and never changing value – so you define it as such. And briefly, you feel good.

The readonly keyword

So following on from the above – let’s also consider the readonly keyword. This works much like the const keyword, with a few important differences:

You can assign a value to this at runtime (e.g. a config value), but you cannot subsequently change the value. Also you can only assign to a readonly field when defining this, or within the scope of a constructor and nowhere else.

readonly fields are not implicitly static (like the const keyword) – but you can choose to define them as such – again you can then either assign the value when defining the variable, or in a static constructor.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: