0

I commonly find myself doing running into this pattern and I was wondering if there was a better way of doing this, or if this is the only way to do it.

Let's say for example I have a Person class.

public class Person
{
  public string name { get; set; }
  public string address { get; set; }
  public string email { get; set; }
  public string phone { get; set; }
}

And I have another Info class.

public class Info
{
  public string name { get; set; }
  public string address { get; set; }
  public string email { get; set; }
  public string phone { get; set; }
}

Let's say I get the information from another source and first put it in data, and then I want to update a Person object with that information.

class Program
{
  static void Main()
  {
    Info info = new Info();
    Person p1 = new Person();
    info = GetInfo(); // some function that populates info
    p1.name = info.name;
    p1.address = info.address;
    p1.email = info.email;
    p1.phone = info.phone;
  }
}

This looks okay at first, but when there's 50 properties to set, the sets take up a chunk of code and I was wondering if there's a way to do it better, or if this is the only way and is acceptable to do this.

I also know that I can just pass in parameters into the constructor, but that means I'll still need to set the properties in the constructor itself.

m1771vw
  • 703
  • 2
  • 11
  • 21
  • 2
    If the properties/fields names match, you can use Reflection or Serialization if you don't care about the performance hit – Camilo Terevinto Apr 16 '19 at 00:09
  • 2
    I'd probably argue why do you have _"`50` properties"_ in the first place - your classes shouldn't be _that flat_. Consider breaking your classes into a heirachy and/or making use of `struct` (the latter allows for **one** step blit operations!) –  Apr 16 '19 at 00:10
  • @MickyD Even if it was a hierarchy, the setters would still need to be done... – Camilo Terevinto Apr 16 '19 at 00:11
  • 1
    @CamiloTerevinto obviously! However there would be significantly less not to a mention `better designed` class model –  Apr 16 '19 at 00:13
  • 1
    Likely the most efficient method to do this is to use a library that is designed for this purpose. I would suggest AutoMapper. – DavidG Apr 16 '19 at 00:16
  • Yes, you might have an Info class, then have Person contain an Info member instead of loose fields. Or more realistically an Address object, a Name object, .... – Dave S Apr 16 '19 at 00:17
  • The first answer to the duplicate question will work with your `Person` and `Info` classes. – Rufus L Apr 16 '19 at 00:32
  • You could use a MemberWiseClone() ...https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.7.2 – Chris Catignani Apr 16 '19 at 00:34

0 Answers0