Cast between Different Interface Implementations

Just finished a cool extension method (at least I think it is), that converts any interface implementation to another implementation.  This can’t be done normally.  Only properties are copied over but you could copy anything that can be accessed via reflection.  I know someone somewhere has already done this but its so rewarding to have a thought, code/test it in 30 minutes and solve a problem in a real app. 

Warning – reflection isn’t known for its efficiency.  If you plan on using this extensively I would suggest caching the reflection calls.

I wrote the first draft in LINQPad (awesome tool!).  Try it out:

void Main()
{
    var vm = new ViewModel { MyData = new[] {“string1”, “string2” }};
    var sd = new SessionData();
    sd.CloneFrom<ISessionData, SessionData>(vm);
    sd.Dump();
}

// Define other methods and classes here

    public static class Object
    {
        public static void CloneFrom<T, TO>(this TO output, T source) where TO : T
        {
            foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
                prop.SetValue(output, prop.GetValue(source, null), null);
        }
    }

public interface ISessionData {
    string[] MyData {get; set;}   
}
public interface IViewModel : ISessionData {
    string UiData { get; set;}
}
public class ViewModel : IViewModel {
    public string[] MyData { get; set;}
    public string UiData { get; set;}
}
public class SessionData: ISessionData {
    public string[] MyData { get; set;}
}

Posted in c#.

Leave a Reply