1

How to I determine if a Type is an ExpandoObject vs a Dynamic object?

This is returning true for both:

public static bool IsDynamicObject(Type type)
{
    return typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type);
}

Example Code for Dynamic Object:

public class Entity
{
    public Guid Id { get; set; }
    public String Name { get; set; }
}

Delta<Entity> x = new Delta<Entity>();
dynamic dynamicX = x;
dynamicX.Name = nameof(Entity);
dynamicX.Id = typeof(Entity).GUID;

Example Code for Expando Object:

dynamic childX = new ExpandoObject();
childX.A = 1;
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Greg Finzer
  • 6,714
  • 21
  • 80
  • 125
  • Why do you mean "a dynamic object"? See [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic) and [here](https://stackoverflow.com/questions/2690623/what-is-the-dynamic-type-in-c-sharp-4-0-used-for) for why I'm asking. `dynamic a = 5;` doesn't have a different type - it's an `int`, but then assigning `a = "hello";` makes it a `string`. – ProgrammingLlama Jul 01 '18 at 03:13
  • Both [`ExpandoObject`](https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx) and [`DynamicObject`](https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject(v=vs.110).aspx) are types derived from `IDynamicMetaObjectProvider`, but they are still types. Check for either – Nkosi Jul 01 '18 at 03:24
  • 1
    Why would you want to know? – Dennis Kuypers Jul 01 '18 at 04:13
  • This is to fix this Github issue: https://github.com/GregFinzer/Compare-Net-Objects/issues/103 – Greg Finzer Jul 01 '18 at 11:27

1 Answers1

0

The ExpandoObject can be casted to a dictionary to get the member names and values

public static bool IsExpandoObject(object objectValue)
{
    if (objectValue == null)
        return false;

    if (IsDynamicObject(objectValue.GetType()))
    {
        IDictionary<string, object> expandoPropertyValues = objectValue as IDictionary<string, object>;
        return expandoPropertyValues != null;
    }

    return false;
}

public static bool IsDynamicObject(Type type)
{
    return typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type);
}
Greg Finzer
  • 6,714
  • 21
  • 80
  • 125