Coppermill
Coppermill

Reputation: 6794

Convert a Dictionary to an Interface

I am trying to convert a Dictionary in to an impmentation of an Interface.

I can get a Dictionary to an Object okay. Doing something like this:

public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
    where T : class, new()
    {
        var someObject = new T();
        var someObjectType = someObject.GetType();

        foreach (var item in source)
        {
            someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);
        }

        return someObject;
    }

    public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

var dictionary = new Dictionary<string, object> {{"Prop1", "hello world!"}, {"Prop2", 3893}};
var someObject = dictionary.ToObject<A>();

But I want to be able to:

var someObject = dictionary.ToObject<iA>();

Anyone know how this can be done?

Upvotes: 0

Views: 1070

Answers (1)

Brandon Cuff
Brandon Cuff

Reputation: 1478

You would need to create a concrete implementation of that interface. You could do this by using the TypeBuilder class.

Alternatively you could use a dynamic type and Impromptu

using ImpromptuInterface;
using ImpromptuInterface.Dynamic;

public interface IMyInterface
{
   string Prop1 { get;  }
}

//Anonymous Class
var anon = new {
         Prop1 = "Test",
}

var myInterface = anon.ActLike<IMyInterface>();

I like Amy's solution a lot better though. Both of the above are much more complex, however they can be done without forcing the caller to specify the actual concrete type.

Upvotes: 1

Related Questions