While watching the video of Anders Hejlsberg, I happened to notice how he apparently uses "var" almost for everything, while I use it extremely sparingly, if at all.
I realize it's mostly a matter of personal preference, but he being the father of C#, I wonder if this is what the language is really supposed to look like... what's your take on "var"?
I only use var for the occasional anonymous type, or when I'm doing complex linq (like grouping) and find that I can't guess the output type.
I prefer explicit types: this is C#, not PHP!
I use it all the time. It makes the code neater when you have a long list of different types of variables.
You should use it all the time, it removes repetition.
VeryLongClassName veryLongClassName = new VeryLongClassName() reads far much worse than
var veryLongclassName = new VeryLongClassName();
It really isn't about preference but about readability. The only time not to use var is when you are returning something like an IAsyncResult or a Dictionary, where it helps to be explicit about what the variable is.
Why repeat the same thing thrice?
I only use it for temporary local variables. Meaning I am going to use it right away and be done with it. But, most of time I prefer strong type. Var is less predictable, which I don't like.
How so? It is just as strongly typed as anything else.
It is not strongly typed at compile time, unless I am wrong. The compiler can validate the type before runtime?
It is strongly typed at assignment time, that is what type inference is, validation has nothing to do with it.
You can only use it within the local scope of a method anyway. If you think about it, the original question is asking if the Chief Architect of the C# Language and .NET Framework is wrong, and does not know what he is doing?
Anders is right, and you should use var wherever it improves readability, and omits triplicate duplication in declaring variables.
It is strongly typed. If you mouse over the variable in the IDE it'll even tell you what type it is, and everything is checked by the compiler the same as if you had explicitly named the type. The type is statically determined by the compiler based on the expression that initializes the variable, and cannot change afterwards.
Don't confuse "var" with "dynamic".
What is the performance penalty of var?
Are these two statements identical in the byte code: StringBuilder something = new StringBuilder(); var something = new StringBuilder();
Also, if they're identical then why use a var at all? Readability is only a mild argument. If you cared about readability you'd be using Visual Basic .Net to begin with.
Last question is - look at this code and tell me what type it would be assigned:
var foo = null;
if(foo == null)
throw new Exception("I dun failed!");
// I only made this exception handling block to create a realistic scenario involving null assignment
var foo = null; will fail, because it is not specific enough for the type to be inferred.
var something = new StringBuilder(); is equivalent to StringBuilder something = new StringBuilder();
You would type that, because it's fewer keystrokes and less redundant.
I use var all the time in my own code. I rarely use it in work code, because, as demonstrated in this thread, most don't understand how var works and make erroneous conclusions about its usage.
@ManipUni: At the moment I am writing in both C# and Visual Basic (not out of choice mind). In general once you have a complex application, long namespaces and classnames are inescapable, and I like to read a line of code without having to use my scroll bar, so var makes things very readable where the verbosity of Visual Basic can be counter to your assertion above.
Your code also would not compile as the first line would raise an error saying that you cannot assign a null value to an implicitly signed variable.
The main place where I'll use var is in a scenario like this:
foreach( KeyValuePair<string, int> item in dictionary )
// Becomes a lot easier with
foreach( var item in dictionary )
I rarely use it for regular locals.
And yeah, the type must be possible to inferred from the initialization of the variable, so Manip's sample doesn't compile.
I see. I thought it is dynamic. But, since it cannot change typy after first call. I will do it. Yeah, it should be cleaner because now I can see all the var similar to Dim.
So var is unusable when you are using any kind of exception handling around initialisation? That seems like a massive drawback to its usefulness.
You're stuck between a rock and hard place, you need to define variables outside of the exception handled blocks (since the compiler cannot predict the route the execution will take within that context) but to a var you must initialise them to a type in order to use them.
How about this example, how would you refactor this into a var version of the same?
You cannot refactor that to use var. Var can only infer the type from the variable's initialization expression, and in this case it has none.
Var was primarily designed for use with LINQ, where the result of LINQ expression can be very complex to express explicitly, or even include anonymous types (in which case it can't be expressed explicitly).
I guess in theory you could create a compiler under which your example works (infer the type using the first assignment if it has no initialization), but that would strain the boundaries of readability and run into issue if determining what's the first assignment is ambiguous.
I use var a lot in foreach statements but have also started to use it more often when my class names are large and it becomes easier to write var repository = new SqlCustomerBookingRepository();
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.