23 June 2014

Difference between Object and Dynamic

object
This keyword is nothing more than a shortcut for System.Object, which is the root type in the C# class hierarchy
Here is a short example that demonstrates some of the benefits and problems of using the object keyword.
object obj = 10;
Console.WriteLine(obj.GetType());
obj = (int)obj + 10;
Dynamic
The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).
dynamic dyn = 10;
Console.WriteLine(dyn.GetType());
dyn = dyn + 10;
dyn = 10.0;
dyn = dyn + 10;
dyn = "10";
dyn = dyn + 10;
This is one of the main differences between object and dynamic –
with dynamic you tell the compiler that the type of an object can be known only at run time, and the compiler doesn’t try to interfere.
As a result, you can write less code.
I want to emphasize that this is no more dangerous than using the original object keyword. However, it is not less dangerous either, so all the type-checking techniques that you need to use when operating with objects (such as reflection) have to be used for dynamic objects as well.
Refer : http://blogs.msdn.com/b/csharpfaq/archive/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords.aspx

No comments: