tags:

views:

1268

answers:

2

When using "var" to declare variables in C#, is there boxing/unboxing taking place?


Also is there a chance of a runtime type mis-match when using var to declare variables?

+20  A: 

No. using var is compiled exactly as if you specified the exact type name. e.g.

var x = 5;

and

int x = 5;

are compiled to the same IL code.

configurator
wrote the same thing but you beat me by a few seconds ;-) +1 and deleted my comment
Matt Briggs
Exactly. The thing is, you *have to* initialize immediately when you use var for local vars, and therefore, the compiler can easily infer the type.
Mehrdad Afshari
You don't have to initialize immediately. You can just declare the variable and assign to it later. But you do have to assign to it in that scope block, and the compiler will determine the type based on that assignment.
Joel Coehoorn
Joel: No, you do have to initialize immediately if you're using var. See section 8.5.1 of the C# 3.0 spec.
Jon Skeet
+10  A: 

var is just a convenience keyword that tells the compiler to figure out what the type is and replace "var" with that type.

It is most useful when used with technologies like LINQ where the return type of a query is sometimes difficult to determine.

It is also useful (saves some typing) when using nested generic declarations or other long declarations:

var dic = new Dictionary<string, Dictionary<int, string>>();
joshperry
Saving typing isn't important IMO - saving visual clutter when *reading* code is, however.
Jon Skeet
But at the cost of making all your variables more specific. It's generally much better to say "Collection c=new LinkedList()" when c is a member vairable--but when it's a local it's not a big deal.
Bill K
@Bill: When c is a memeber variable, you can't use var so you have no choice.
configurator
Cool, didn't know that. Not a problem then. (Sorry, I'm java although I like a lot of the features I hear about in C#)
Bill K
var isn't just a convenience, when used with anonymous types (such as those created with LINQ Select projection) there is no other choice but to use var.
AnthonyWJones