I have 2 classes Customer and Person(share exactly the same properties and these properties should be filled in by a request
I would like to write a generic method like
//Usage Customer myCustomer =CreateCustomerOrPerson<Customer>(myRequest)
//Usage Person myPerson =CreateCustomerOrPerson<Person>(myRequest)
public static T FillPropertiesOfCustomerOrPerson<T>(Request request)
{
//not sure how I would I do it to fill the properties.
// T a = default(T);
//a.Name=request.Name;
//a.Surname=request.Surname;
// if (a is Customer)
//{
//?
/// }
return (T)a;
}
How would you write this generic method to avoid having 2 methods (one for customer and one for person)?
Edit
I have no control over these classes. I just need to fill the properties and I was wondering if I could write a generic method rather than 2 specific ones.
Given the requirements, your options are somewhat limited. If you don’t want to make use of the
dynamickeyword (due to .NET version or whatever), you could do this old-style and use reflection. A possible implementation of that follows:Optionally, you could remove the
where T : new()and replace the instantiation code with something like this: