using var has any side effects? [duplicate]
Possible Duplicate:
C# 'var' vs specific type performance
Are there any performance costs (in terms of type conversion, etc.) if I write the line
SqlConnection c = new SqlConnection(connectionString))
as
var c = new SqlConnection(connectionString))
No. The compiled IL is identical.
The only potential side effect is in the case of inheritance, if you're variable definition is a base class, and you instantiate a subclass. If you do:
BaseClass item = new DerivedClass();
This will potentially act differently than:
var item = new DerivedClass();
This is because the second compiles to:
DerivedClass item = new DerivedClass();
In most cases, it should behave identically (due to the Liskov substitution principle). However, if DerivedClass
uses method hiding it is possible to have a change in behavior.
No. The compiler knows at compile time what var
should be (the return of new SqlConnection
is, in fact, SqlConnection
. When the compiler knows the type of the right hand side, you can use var
.
This has no runtime performance implications
I believe var is processed at compile time, so it is simply a shortcut for writing the code. This means that the compiled version is identical.
精彩评论