Search code examples
c#.net.net-3.5interfacecopying

Using an interface to convert an object from one type to another?


Suppose I have two classes with the same interface:

interface ISomeInterface 
{
    int foo{get; set;}
    int bar{get; set;}
}

class SomeClass : ISomeInterface {}

class SomeOtherClass : ISomeInterface {}

Suppose I have an instance of ISomeInterface that represents a SomeClass. Is there an easy way to copy that into a new instance of SomeOtherClass without copying each member by hand?

UPDATE: For the record, I'm not trying to cast the instance of SomeClass into the instance of SomeOtherClass. What I'd like to do is something like this:

ISomeInterface sc = new SomeClass() as ISomeInterface;
SomeOtherClass soc = new SomeOtherClass();

soc.foo = sc.foo;
soc.bar = soc.bar;

I just don't want to have to do that for each by hand as these objects have lots of properties.


Solution

  • "Would you be able to give me an example of how I can do that (or at least point me towards the right methods to be using)? I don't seem to be able to find them on MSDN" – Jason Baker

    Jason, something like the following:

    var props = typeof(Foo)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
    foreach (PropertyInfo p in props)
    {
         // p.Name gives name of property
    }
    

    I'd suggest writing a tool to spit out the code you need for a copy constructor, as opposed to doing it reflectively at runtime - which would be less performant.