简体   繁体   中英

object and var difference in C#

objectvar之间有什么区别?

  • var - Not specifying the type explicitly. Letting compiler figure out what that type is.
    • Type is fixed at design time and cannot refer to object of other type.
    • As Pauli noted in a comment, you get intelliSense .
    • Must be initialized. var i; won't compile.
    • Cannot be used as return type of a method.
    • Must be a local variable. Not a field or property.
    • Works great with Anonymous Types . You get intelliSense .
  • object - System.Object .
    • Can be used to refer any type at runtime.
    • Here you don't get intelliSense .

Example:

var i = 0; // i is of type `System.Int32`.  Same as "int i = 0;"
i = "Some String"; // Compile time error.

object o = 0;  
o = "Some String"; // Works
  • object will be determined in runtime, but var determined in compile time.

for example:

var i = 2;
object j = 2;

and you look at it in ildasm:

  IL_0000:  nop
  IL_0001:  ldc.i4.2
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.2
  IL_0004:  box        [mscorlib]System.Int32
  IL_0009:  stloc.1

You can see object item should be boxed and var item no need to boxing.

MSDN for object and var

  • Also you can do:

      object i; i = 2; 

    but you can't do:

      var i; i = 2; 

    you will get compile error.

  • Object is type which all things in .Net inherited from it, so you can do object x = y for any type of y because of inheritance, but var is a keyword for implicit type definition, for example var i = 2 means int i = 2.

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