Difference between objects and var in C #

What is the difference between object and var ?

+4
source share
2 answers
  • var - Do not specify the type explicitly. Letting the compiler know what type it is.
    • The type is fixed at design time and cannot reference an object of another type.
    • As noted in Pauli comment, you get intelliSense .
    • Must be initialized. var i; will not compile.
    • Cannot be used as return type of method.
    • There must be a local variable. Not a field or property.
    • Works Anonymous Types with Anonymous Types . You get intelliSense .
  • object - System.Object .
    • Can be used to refer to any type at runtime.
    • You are not getting 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 
+7
source
  • An object
  • will be determined at runtime, but var is defined at compile time.

eg:

 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 that the object should be placed in the box, and the var element is not needed for the box.

MSDN for object and var

  • You can also:

      object i; i = 2; 

    but you cannot do:

      var i; i = 2; 

    You will get a compilation error.

  • An object is a type in which .Net inherited all things from it, so you can make an object x = y for any type y because of inheritance, but var is a keyword for implicit type determination, for example, var i = 2 means int i = 2.
+1
source

Source: https://habr.com/ru/post/1332725/


All Articles