Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
Jason Baker Avatar asked Nov 19 '08 22:11

Jason Baker


1 Answers

You can create implicit operators in each class to do the conversion for you:

public class SomeClass
{
    public static implicit operator SomeOtherClass(SomeClass sc)
    {
        //replace with whatever conversion logic is necessary
        return new SomeOtherClass()
        {
            foo = sc.foo,
            bar = sc.bar
        }
    }

    public static implicit operator SomeClass(SomeOtherClass soc)
    {
        return new SomeClass()
        {
            foo = soc.foo,
            bar = soc.bar
        }
    }
    //rest of class here
}

and then SomeOtherClass soc = sc; and vice versa would work.

like image 127
Adam Lassek Avatar answered Nov 02 '22 13:11

Adam Lassek