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

前端 未结 6 688
生来不讨喜
生来不讨喜 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题