Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build an object from another object in C# using generic code

Let's say I have an object of Type User that looks like this:

User {
   Name = "Bob",
   Email = "[email protected]",
   Class = NULL
}

Can anyone think of a way to take that object and create an object like this:

User {
   Name = "Bob",
   Email = "[email protected]"
}

Using entirely generic code? Meaning, I don't want to hard code anything to do with the Type, or the Properties because this code would need to be applied to every Entity on my site. (the "User" type is an Entity by the way, so use that if it helps you code this better).

I'm just trying to come up with a solution to a problem I have and I BELIEVE that Stub Entities may fix the problem, but I need to do it without hard coding any Types or Properties.

like image 839
James P. Wright Avatar asked Feb 15 '26 02:02

James P. Wright


1 Answers

Use reflection to achieve this:

public void CopyValues<TSource, TTarget>(TSource source, TTarget target)
{
    var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);

    foreach (var property in sourceProperties)
    {
        var targetProperty = typeof(TTarget).GetProperty(property.Name);

        if (targetProperty != null && targetProperty.CanWrite && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))
        {
            var value = property.GetValue(source, null);

            targetProperty.SetValue(target, value, null);
        }
    }
}
like image 139
Peter Avatar answered Feb 16 '26 14:02

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!