Reputation: 259
Can anyone briefly explain the difference between following 2 statements and also when should I use one over the other?
For example, I have a Person class and want to instantiate Person class in another class
Person person = new Person();
var person = new Person();
Upvotes: 0
Views: 1591
Reputation: 186668
There's no difference, it's just a syntactic sugar:
…An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type…
http://msdn.microsoft.com/library/bb383973.aspx
Upvotes: 2
Reputation: 18411
Please reference this doc
The first is explicit declaration while the second is implicit(the compiler will decide the object). Otherwise they are equivalent.
Upvotes: 1
Reputation: 20722
Both are compiled to the same MSIL code. The only difference is a possible convenience for you while writing source code - if you decide to change the type of p
later on, you only have to replace Person
once in the constructor call and you can leave the variable declaration intact when using var
.
That said, var
goes along with a slight decrease in legibility, as you cannot see the type of p
instantly any more at the beginning of your line. Therefore, restrict your use of var
to occasions where it really saves some typing, such as for complicated nested generic types.
Note that, if you do not initialize your variable right away (in the same statement where the variable is declared), you cannot use var
as the compiler cannot infer the type of the variable.
Upvotes: 2
Reputation: 7619
no difference here. var
is translated in Person
during the compile time. I usually use var
to make the refactoring of code faster, I mean that if you decide to change the type of p
, you can simply change the right side and let var
.
Upvotes: 0