Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone object to another object but exclude some properties?

Tags:

c#

cloning

I would like to clone an Object to another object but exclude a property from the original object. example if object A has Name, Salary, Location, then the cloned object should have only Name and salary properties if i excluded the Location Property. Thanks.

like image 487
user282807 Avatar asked Oct 28 '25 01:10

user282807


1 Answers

Here's an extension method that I use to do this:

public static T CloneExcept<T, S>(this T target, S source, string[] propertyNames)
{
    if (source == null)
    {
        return target;
    }
    Type sourceType = typeof(S);
    Type targetType = typeof(T);
    BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;

    PropertyInfo[] properties = sourceType.GetProperties();
    foreach (PropertyInfo sPI in properties)
    {
        if (!propertyNames.Contains(sPI.Name))
        {
            PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags);
            if (tPI != null && tPI.CanWrite && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType))
            {
                tPI.SetValue(target, sPI.GetValue(source, null), null);
            }
        }
    }
    return target;
}

You might also check out Automapper.

And here's an example of how I use the extension.

var skipProperties = new[] { "Id", "DataSession_Id", "CoverNumber", "CusCode", "BoundAttempted", "BoundSuccess", "DataSession", "DataSessions","Carriers" };
DataSession.Quote = new Quote().CloneExcept(lastSession.Quote, skipProperties);

Since this is implemented as an extension method, it modifies the calling object, and also returns it for convenience. This was discussed in [question]: Best way to clone properties of disparate objects

like image 50
B2K Avatar answered Oct 29 '25 15:10

B2K



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!