Tuesday, February 15, 2011
Difference between Dynamic, Object and Var
Object
The object –keyword represents the System.Object type, which is the root type in the C# class hierarchy.
This keyword is often used when there’s no way to identify the object type at compile time, which often happens in various interoperability scenarios.
You need to use explicit casts to convert a variable declared as object to a specific type
object objExample = 10;
Console.WriteLine(objExample.GetType());
This obviously prints System.Int32. However, the static type is System.Object, so you need an explicit cast here:
objExample = (int)objExample + 10;
You can assign values of different types because they all inherit from System.Object:
objExample = "test";
VAR
The var keyword, since C# 3.0, is used for implicitly typed local variables and for anonymous types.
When a variable is declared by using the var keyword, the variable’s type is inferred from the initialization string at compile time.
The type of the variable can’t be changed at run time. If the compiler can’t infer the type, it produces a compilation error:
var varExample = 10;
Console.WriteLine(varExample.GetType());
This prints System.Int32, and it’s the same as the static type.
No cast is required because varExample’s static typed is System.Int32:
varExample = varExample + 10;
This line doesn’t compile because you can only assign integers to varExample:
varExample = "test";
DYNAMIC
The dynamic keyword, introduced in C# 4.
In fact, the dynamic type uses the System.Object type under the hood, but unlike object it doesn’t require explicit cast operations at compile time, because it identifies the type at run time only
dynamic dynamicExample = 10;
Console.WriteLine(dynamicExample.GetType());
This prints System.Int32.
In the following line, no cast is required, because the type is identified at run time only:
dynamicExample = dynamicExample + 10;
You can assign values of different types to dynamicExample:
dynamicExample = "test";
What sometimes causes confusion is that all of these keywords can be used together—they’re not mutually exclusive.
dynamic dynamicObject = new Object();
var anotherObject = dynamicObject;
What’s the type of anotherObject? The answer is: dynamic.
Remember that dynamic is in fact a static type in the C# type system, so the compiler infers this type for the anotherObject. It’s important to understand that the var keyword is just an instruction for the compiler to infer the type from the variable’s initialization expression; var is not a type
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment