locked
FAQ Item: What are the differences between dynamic and object keywords? RRS feed

  • Question

  • What are the differences between dynamic and object keywords?
    Sunday, June 20, 2010 11:53 AM

Answers

  • object keyword is nothing more than a shortcut for System.Object, which is the root type in the C# class hierarchy. However, not everything in C# derives from object, you can get more information on this from Eric Lippert’s blog article http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx .

    Even if we know an object type variable stores an int value, we still have to first convert the object variable to int type and then do int-type operation on it. Otherwise, the compiler will detect it breaks the rule.

    object o = 10;

    o = o+10; //cannot compile for “operator + cannot apply to operands of type object and int”

     

    In C# 4.0, the dynamic is introduced. In compile time, we do not need to convert the dynamic type variable to the specified type and then perform the operation.

    dynamic dyn = 10;

    dyn = dyn + 10; //compile OK.

    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. And 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.

     

    A detailed blog article about this:

    http://blogs.msdn.com/csharpfaq/archive/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords.aspx

     

    For more FAQ about Visual C# General, please see Visual C# General FAQ

    • Marked as answer by MSDN FAQ Sunday, June 20, 2010 11:54 AM
    Sunday, June 20, 2010 11:53 AM