I find it amazing that .NET 3.5 has been out for over a year and people still don’t understand the “var” keyword.
Just last week I got a comment on one of my videos asking why I used “var” so much. Isn’t that only supposed to be used when you don’t know what the return type is going to be?
Clearly, this person does not understand what “var” does or how it should be used.
You see, the var keyword can ONLY be used when you know the return type. It isn’t the same as a variant in VB6.
var str = "abe";
gets converted to
string str = "abe";
In fact if you write
var str; str = "abc";
You will get the compiler error
“Implicitly typed local variable must be initialized.”
Why? Because the compiler looks at the type of the variable or constant on the right hand side to determine what the variable type is so that it can strongly type the variable.
There isn’t any way of using “var” as a “figure this out at runtime” specified. Everything happens at compile time based on what the compiler can determine about the variable type being used on the right-hand side.
In my day-to-day code, I don’t use “var” all that much. It kind of looked cool when I started but old habits die hard and with intellisense it doesn’t really buy me that much in terms of saving keystrokes while I’m writing my code. It kind of makes the code hard to read, too.
So while the understanding is wrong, the practice is right. Only use var when you NEED it.
If you needed a variable that looked like a variant, what would you use?
If you clearly understand object oriented programming, you know this. The Object class is the parent class of all other types in .NET. Therefore you can assign any variable to to a variable declared as type Object.
Other places talking about CSharp VAR:
Var Wars – Abuse of the CSharp var – CSharp 3.0 introduced the var keyword for declaring variables without having to explicitly specify the type. This was done for using anonymous types returned from LINQ queries. Now, I am seeing many developers use it all over their code …
Local Type Inference (var keyword) (C#) – C# Language Features Tutorials.
Usage of the var Keyword in C# – Blaenk Denum – The question is, when should one use the var keyword? Take a look at this Stack Overflow question: What’s the point of the var keyword? In it, people note that using var can actually save you some time and in some cases make code a lot …