Search code examples
c#.netlinqextend

How can I extend a field of a class?


Suppose I have a List of Person (which is a class). It contains about 20 field (Name, Surname, Age, DateOfBirthdate, and so on). So I got this list:

var listOfPersons= MyContext.Persons.Cast<Person>();

Now, I need to iterate through this List, and for each Person adding a new field (which it is not present in the class), called, let's say, CurrentDateTime.

I could create a new object, with the new field, and "copy & paste" values from Person to the new Class. Somethings like:

PersonNew newPerson = new PersonNew("Name", "Surname", "Age", "DateOfBirthdate", ... "CurrentDateTime");

But this is very bad if in the future I change the Person class. So, is there a strategy to "extending Person" with a new field? That takes the Person instance (whatever it is) and adds the new field?


Solution

  • You can create some static method that create PersonNew from Person using Automapper.

    public class PersonNew : Person
    {
        public static PersonNew CreateFromPerson(Person person, DateTime currentDateTime)
        {
            var newPerson = Mapper.Map<PersonNew>(person);
            newPerson.CurrentDateTime = currentDateTime;
        }
    }