Const correctness in C#
One would think that a modern programming language (especially one not hindered by backwards compatibility with C) would implement the obviously useful const facility.
Some people see const simply as a way to give the compiler optimization hints. I see it as much more. Const is a bullet in the arsenal of preemptive bug prevention. Const isn't an cure-all by any means, but it helps eliminate certain typo (or worse, "thinko") bugs in which you alter a variable, even though your intention was to leave it untouched. By typing 5 extra characters, const is an effortless way to prevent this bug.
When you write code for a living, you clutch onto any good bug prevention tricks, and are loathe to let them go. That's why I'm so appalled that C# doesn't let me use const.
When asked why C# didn't have const, the lead architect sort of looked at his shoes and mumbled that it was too hard to guarantee constness, and that C++ cheats by letting you override it.
Sheesh.
How do I enforce const correctness in C#?
Answer: you can't.
CLR Design Choices (google cache)
Anders Hejlsberg, the lead C# architect, talks with Bruce Eckel and Bill Venners about IL instructions, non-virtual methods, unsafe code, value types, and immutables.The article where the imagined shoe-gazing took place.
Why doesn't C# have "const"?
Discussion thread where vitriol is spewed at a hypothetical VB programmer named "Mort." Mort is an imaginary dullard who hacks his way through projects, and for whom "const" would be an impossible-to-understand roadblock.
3 Comments:
At 8/17/2005 6:31 PM, sigfpe said…
Some people see const simply as a way to give the compiler optimization hints.
I think these people are wrong. A compiler has to do a dataflow analysis to analyse your code. It makes its own decisions about what is constant and can't use 'hints'. And const doesn't mean 'constant' anyway so it's not obvious how a compiler can exploit it. For example we have mutables, const casts and const-references to non-consts. As you point out, const is about how you write code. Also, a const X is a distinct type from an X which means you can use overloading to implement algorithms for const and non-const objects differently - something that is sometimes useful.
At 8/23/2005 10:48 PM, Zoe Brain said…
I prefer languages where parameters are either "in" (no change), "out" (original value is irrelevant), or "in out" - anything goes.
At 7/28/2009 7:21 PM, Anonymous said…
So you get pissed because C# don't have a c++-like const keyword? Const correctness is a programming concept rather than a language feature. http://stackoverflow.com/questions/114149/const-correctness-in-c
Post a Comment
<< Home