简体   繁体   中英

Difference between Var type and object type in C#

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();

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.

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

Please reference this doc

The first is explicit declaration while the second is implicit(the compiler will decide the object). Otherwise they are equivalent.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM