- It can only be used on variables initialized on the same line
- It is statically typed when initialized, so strong typing is maintained
for (var i = 0; i < 400; i++)
{
if (i == 0)
Console.Write(i.GetType().Name);
}
Since the var i is in the range of 0 to 399, I hoped the compiler would realize that it could use a short (or even a ushort) when it typed it. It does not.
The reason is pretty simple, really. It's not intelligent. Since I assigned 0, which is by default an Int32, the variable i was statically typed as an Int32. If I change it to read var i = 0u, it will type it as a UInt32.
This isn't really surprising, but it's a little disappointing. My basic idea was that if the size of the loop changed (statically) in the future, I could save the trouble of changing the variable type manually. That is, if the compiler automatically picked the smallest variable type required.
In any case, I dislike the use of var immensely. I understand it is required for LINQ, but in any other case, it looks like pure laziness. One article I read said that typing "var" instead of "Dictionary
No comments:
Post a Comment