This is the first in what I hope will become
a series on the new language features in C# 3.0 used in
.NET 3.5 /
Visual Studio 2008.
One thing I am not intending to cover is LINQ. Just because the
blogosphere has been buzzing with LINQ articles since the early days of
"Orcas". And with good reason I hasten to add!
Where I am starting is with the var keyword.VB6 veterans will remember the
Variant type. A
Variant could contain anything, even
Object. While this was
sort of useful, my memory of it is as a synonym for:
I can't be bothered, lets just stick it in a Variant and deal with it later.
There was also a performance impact of using the special Variant type, they were large in memory and have an overhead of extra runtime checking that added up; like when assigned inside a loop for example. They were also a special case in their un-assigned form, taking on the value
Empty (test with
IsEmpty()) vs
Nothing (test with
Is Nothing).
So when I saw
var added to C# I raised my eyebrows in the way a Fed might, when the beagle sits quietly next to your suitcase at the airport.
Most of the time you see it in the samples, it is used when returning an Anonymous Type from a LINQ query. And this is the clue!
var is not itself a type, but instead
it is a signal to the compiler to infer the type of an operation, and substitute in the required type. It does not even have to be an Anonymous Type. Consider the following simple example:
var result = 10 / 2.0;
Console.WriteLine(result.ToString());
By the time this code is compiled,
var is replaced with
double. In fact, the Intellisense on result will be correct for it being a
double.
To confirm this, looking at those lines of the assembly in
Lutz Roder's Reflector show the following after disassembly:
double result = 5.0;
Console.WriteLine(result.ToString());OK, so var can be used independant of Anonymous Types,
but why would you want to be less explicit in typing your variables? Consider the following fictitious example:
DatabaseRequestService req = DatabaseRequestService.CreateFrom(value);And compare it with the equivalent line using
var:
var req = DatabaseRequestService.CreateFrom(value);Here,
var leads itself to much more readable syntax with the same typing, Intellisense, and everything else!
Listening To: Róisín Murphy