object and var difference in C#
What is the difference between object
开发者_开发百科and var
?
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 getintelliSense
. - 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 getintelliSense
.
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.
精彩评论