Alex Rivera | Logout

What is the point of a constant in C#

Asked 2010-03-28T04:08:50.187
14

Can anyone tell what is the point of a constant in C#?

For example, what is the advantage of doing

const int months = 12;

as opposed to

int months = 12;

I get that constants can't be changed, but then why not just... not change it's value after you initialize it?

Edit
Report

1 Answer

8

If you never make mistakes, nobody on any team you work with ever makes mistakes, you never forget the exact purpose of a variable you've defined even after coming back to code you haven't looked at in months or years, and you and everyone you work with 100% reliably recognizes, understands and follows your intention of never changing a const value when you haven't bothered to use a built-in language construct that both clearly indicates and enforces constness, then no, there's no point.

If any one of those things ever turns out not to be the case, that's the point.

As for me, I find that even when I'm at my most lucid, remembering more than seven things at once is pretty close to impossible, so I'll take all the help I can get to prevent mistakes, especially when the cost is a single keyword. If you're smarter than me, and you never have to work on a team with someone less smart than you, then do whatever you want.

In some cases, there may be some compiler optimizations that can be done based on constness (constant folding, for one, which collapses expressions consisting of constants at compile-time). But usually, that's not the point.

answered 2010-03-28T06:00:57.503

Your Answer