Programming University

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.