What is the difference between object
and var
?
var
- Not specifying the type explicitly. Letting compiler figure out what that type is.
Pauli
noted in a comment, you get intelliSense
.var i;
won't compile.Anonymous Types
. You get intelliSense
.object
- System.Object
.intelliSense
.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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With