Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface property copy in c#

Tags:

c#

interface

I've been working with C# for many years now, but just come across this issue that's stumping me, and I really don't even know how to ask the question, so, to the example!

public interface IAddress
{
  string Address1 { get; set; }
  string Address2 { get; set; }
  string City { get; set; }
  ...
}

public class Home : IAddress
{
  // IAddress members
}

public class Work : IAddress
{
  // IAddress members
}

My question is, I want to copy the value of the IAddress properties from one class to another. Is this possible in a simple one-line statement or do I still have to do a property-to-property assignment of each one? I'm actually quite surprised that this seemingly simple thing has stumped me like it has... If it's not possible in a concise way, does anyone have any shortcuts they use to do this sort of thing?

Thanks!

like image 892
opedog Avatar asked Aug 13 '09 15:08

opedog


1 Answers

Here's one way to do it that has nothing to do with interfaces:

public static class ExtensionMethods
{
    public static void CopyPropertiesTo<T>(this T source, T dest)
    {
        var plist = from prop in typeof(T).GetProperties() where prop.CanRead && prop.CanWrite select prop;

        foreach (PropertyInfo prop in plist)
        {
            prop.SetValue(dest, prop.GetValue(source, null), null);
        }
    }
}

class Foo
{
    public int Age { get; set; }
    public float Weight { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
        return string.Format("Name {0}, Age {1}, Weight {2}", Name, Age, Weight);
    }
}

static void Main(string[] args)
{
     Foo a = new Foo();
     a.Age = 10;
     a.Weight = 20.3f;
     a.Name = "Ralph";
     Foo b = new Foo();
     a.CopyPropertiesTo<Foo>(b);
     Console.WriteLine(b);
 }

In your case, if you only want one set of interface properties to copy you can do this:

((IAddress)home).CopyPropertiesTo<IAddress>(b);
like image 140
plinth Avatar answered Oct 04 '22 21:10

plinth