简体   繁体   中英

Difference between “var” and “object” in C#

Is the var type an equivalent to Variant in VB? When object can accept any datatype, what is the difference between those two?

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var . An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; //implicitly typed
int i = 10; //explicitly typed

var isn't object

You should definitely read this : C# 3.0 - Var Isn't Object

Nope - var just means you're letting the compiler infer the type from the expression used to assign a value to the variable.

It's just syntax sugar to let you do less typing - try making a method parameter of type " var " and see what happens :]

So if you have an expression like:

var x = new Widget();

x will be of type Widget , not object .

其他答案是正确的,我只想补充一点,你可以实际将光标放在'var'关键字上,然后点击F12跳转到推断的类型声明。

Adding to the post.

Parent p = new Parent(); 
Child c  = new Child();//Child class derives Parent class
Parent p1 = new Child();

With above you can only access parent (p1) properties eventhough it holds child object reference.

var p= new Parent();
var c= new Child();
var p1 = new Child();

when using 'var' instead of class, you have access to both the parent and child class properties. it behaves like creating object for child class.

一个区别是Boxing和Unboxing with Object。

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