Comments, how-to's, examples, tools, techniques and other material regarding .NET and related technologies.
Wednesday, January 30, 2008
const == static?
Sometimes it can be the simple things that surprise. Ok, maybe you are one of those geniuses who knew it all the time. If that is the case don't bother reading this post. For all mere mortals go ahead.
When writing code in C# on the surface you would assume that const and static mean two different things. But in reality there is a connection.
As soon as you declare a field to be const it becomes static.
The explanation is actually quite simple. If a field is declared const then its value is the same in all instances of that class. If that is the case a conceptual optimization can take place by simply declaring such a field static. If the value is the same it can be share across all instances.
Sounds a bit confusing but it actually makes sense. This is not necessarily obvious at face value. Having worked with C++, Java, and C# over years it just became apparent when working with the type system and reflection in .NET.
What I learn from that? There is always a little gem waiting to be discovered!
Now here is some food for an additional thought: Can a static field be automatically const? If so, why? If not, why not?
Labels:
Technology
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment
All comments, questions and other feedback is much appreciated. Thank you!