They both compile to the same thing. When using var
, you're simply letting the compiler infer the type at compile time. That may add a little bit of time to compilation (I haven't actually tested that part), but will have no impact at run-time.
The advantage of the former (which is what I prefer personally) is when you start to deal with long Type names:
var conn = new System.Data.SqlConnection(connString);
Is a lot less keystrokes and easier to read than:
System.Data.SqlConnection conn = new System.data.SqlConnection(connString);
In addition, without var
, using Anonymous Types would be nearly impossible:
var someObj = new { Name = "Test", Saying = "Hello World!" };
There are definitely times that I prefer to use the full type name instead of var
though. The most notable of which is when handling a return value of a method. If it is not clear from the name of the method what the type of the return value to be, I will explicitly define it. That reduces confusion in case anything changes down the road.