Arseni Mourzenko
Arseni Mourzenko

Reputation: 52311

How to know if the type parameter is dynamic?

It seems that every time dynamic is used by the caller of a generic method, the type actually used is a simple object. For example, the code:

public static void Main()
{
    Program.DoSomething<int>();
    Program.DoSomething<object>();
    Program.DoSomething<dynamic>();

    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}

public static T DoSomething<T>() where T : new()
{
    Console.WriteLine(
        "The type is: {0}; equal to object: {1}.",
        typeof(T).FullName,
        typeof(T) == typeof(object));

    dynamic result = new ExpandoObject();
    result.Hello = "Hello";
    result.Number = 123;

    try
    {
        return (T)result;
    }
    catch (Exception)
    {
        Console.WriteLine("Can't cast dynamic to the generic type.");
        return new T();
    }
}

produces:

The type is: System.Int32; equal to object: False.
Can't cast dynamic to the generic type.
The type is: System.Object; equal to object: True.
The type is: System.Object; equal to object: True.

How is it possible to determine, within the generic method, whether the type parameter is dynamic or an ordinary object?

Upvotes: 4

Views: 248

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062512

No, you cannot. Dynamic is all in the eye of the beholder (meaning: the compiler). It is implemented as dynamic. You can, however, check for IDynamicMetaObjectProvider: if an object implements that, the caller is probably talking about dynamic. Unfortunately, reflection also works inside dynamic, but will not involve IDynamicMetaObjectProvider at all.

Upvotes: 4

Related Questions