Type Inference for Constants in C#
In C# 3.0 (part of .NET 3.5) we were introduced to a new keyword: var. The var keyword enabled a really nice feature called "type inference", whereby you can declare a variable without having to explicitly state its type. In trivial examples like this, it doesn't feel like it saves you much:
var i = 3; // i is an int
... but where it saves a lot of typing and redundancy is when you have a reasonably complex type, like this:
var x = new Dictionary<string, Func<string, IList<int>>>();
This saves you from having to repeat a long type name on both sides of the "=" sign, which adds to code readability.
Now, some would argue that var can be evil. For example, when you use it like this, it's very difficult for the reader of your code to tell what type your variable is:
var foo = DoStuff();
... but then, that's more a problem of method naming than anything. If that method had been called "GetFoo" then perhaps it would be more obvious what type "foo" is.
Anyway, a feature that has been around in Pascal forever and would be handy to have in C# is type inference for constants. Right now if you want to declare a constant, you use the const keyword as a modifier for a variable declaration, like this:
const double pi = 3.14159;
But since constants have to be initialised at the same time that they're declared, it makes sense to me to adapt the type inference rules to apply to the const keyword too. Then we'd have the option of declaring constants like this:
const pi = 3.14159;
It's a small change, but I don't think it would be particularly hard to pull off. What do you think?
No new comments are allowed on this post.
Comments
TimothyP
I agree... more then once I found myself typing var in front of a constant only to have the compiler nag at me. So +1