In most cases, using var for simple types actually helps readability and we must not forget that there is also no performance penalty for using var .
var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.
This does not slow down the compiler. The compiler already has to know the result type of the expression, in order to check compatibility (direct or indirect) of the assignment.
One of the main advantages of the VaR metric is that it is easy to understand and use in analysis. This is why it is often used by investors or firms to look at their potential losses. The metric can also be used by traders to control their market exposure.
There's no extra IL code for the var
keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.
The only trick is that var
will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.
As Joel says, the compiler works out at compile-time what type var should be, effectively it's just a trick the compiler performs to save keystrokes, so for example
var s = "hi";
gets replaced by
string s = "hi";
by the compiler before any IL is generated. The Generated IL will be exactly the same as if you'd typed string.
As nobody has mentioned reflector yet...
If you compile the following C# code:
static void Main(string[] args)
{
var x = "hello";
string y = "hello again!";
Console.WriteLine(x);
Console.WriteLine(y);
}
Then use reflector on it, you get:
// Methods
private static void Main(string[] args)
{
string x = "hello";
string y = "hello again!";
Console.WriteLine(x);
Console.WriteLine(y);
}
So the answer is clearly no runtime performance hit!
For the following method:
private static void StringVsVarILOutput()
{
var string1 = new String(new char[9]);
string string2 = new String(new char[9]);
}
The IL Output is this:
{
.method private hidebysig static void StringVsVarILOutput() cil managed
// Code size 28 (0x1c)
.maxstack 2
.locals init ([0] string string1,
[1] string string2)
IL_0000: nop
IL_0001: ldc.i4.s 9
IL_0003: newarr [mscorlib]System.Char
IL_0008: newobj instance void [mscorlib]System.String::.ctor(char[])
IL_000d: stloc.0
IL_000e: ldc.i4.s 9
IL_0010: newarr [mscorlib]System.Char
IL_0015: newobj instance void [mscorlib]System.String::.ctor(char[])
IL_001a: stloc.1
IL_001b: ret
} // end of method Program::StringVsVarILOutput
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With