CONSTANTly learning

I Found an interesting tid-bit of information about C# constants today when a member of my Programming Tutorial Group asked why my tutor hadn’t used some code like:

const string MaximumYear = DateTime.Now.Year.ToString();

in order to have the MaximumYear variable as a string representation of the current year. (The context was the release date of a film in a DVD library. Obviously you cannot have a film in the library that has been released in the future).

The reason is because constants are set at compile time, rather than runtime. Therefore if you compiled the above code today MaximumYear would always contain the value “2012”. I can see that this would confuse a lot of people, had you asked me I would have assumed that constants would be initialized at Runtime, but apparently not.

I can see some use for this though, such as setting “Build Times” in the about section of a program autonomously.

Danny

Advertisements

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s