The difference between "var" and "object" in C #

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

+42
c # types
12 Oct '09 at 5:34
source share
6 answers

Starting with Visual C # 3.0, variables declared in a method scope can be of the imp type var . An implicitly typed local variable is strongly typed in the same way as if you 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 is not an object

You should definitely read the following: C # 3.0 - Var is not an object

+49
Oct 12 '09 at 5:36
source share
— -
+10
Aug 25 '14 at 9:49 on
source share

Nope - var simply means that you let the compiler infer the type from the expression used to assign the value to the variable.

It's just syntactic sugar that allows you to do less input - 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 .

+6
Oct 12 '09 at 5:36
source share

The other answers are correct, I just wanted to add that you can hover over the keyword 'var' and press F12 to go to the declaration of the intended type.

+6
Oct 12 '09 at 5:49
source share

Adding to the message.

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

Using the above, you can only access parent (p1) properties, although it does contain a reference to a child object.

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

when using "var" instead of a class, you have access to the properties of the parent and child classes. it behaves like creating an object for a child class.

0
May 6 '16 at 6:06
source share

one difference is Boxing and Unboxing with Object.

0
Dec 12 '16 at 4:54 on
source share



All Articles