3

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.

Venkat
  • 2,549
  • 2
  • 28
  • 61
user282807
  • 905
  • 3
  • 13
  • 26

2 Answers2

3

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

B2K
  • 2,541
  • 1
  • 22
  • 34
0

if you are talking about java then you may try "transient" keyword. atleast this works for serialization.

Kunal
  • 3,475
  • 21
  • 14
  • @user282807 next time set the appropriate language tag for the question if it is language specific - saves you parsing irrelevant answers and other from writing them ;-) thankfully a nice community member already added that tag for you this time – mbx Jan 23 '18 at 12:35