Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object and var difference in C#

What is the difference between object and var?

like image 817
stackBest2 Avatar asked Feb 25 '23 13:02

stackBest2


2 Answers

  • 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
like image 129
decyclone Avatar answered Feb 28 '23 02:02

decyclone


  • 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.
like image 36
Saeed Amiri Avatar answered Feb 28 '23 02:02

Saeed Amiri