lundi 15 avril 2019

Is there a better way to set many properties?

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.

Aucun commentaire:

Enregistrer un commentaire