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

前端 未结 6 655
生来不讨喜
生来不讨喜 2020-11-29 12:06

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

相关标签:
6条回答
  • 2020-11-29 12:26

    Well documented from codeproject

    For more details have a look at http://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp

    0 讨论(0)
  • 2020-11-29 12:27

    one difference is Boxing and Unboxing with Object.

    0 讨论(0)
  • 2020-11-29 12:32

    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

    0 讨论(0)
  • 2020-11-29 12:35

    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.

    0 讨论(0)
  • 2020-11-29 12:36

    The other answers are right on, I'd just like to add that you can actually put your cursor on the 'var' keyword and hit F12 to jump to the inferred type declaration.

    0 讨论(0)
  • 2020-11-29 12:45

    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.

    0 讨论(0)
提交回复
热议问题