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.
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