Montag, 19. Juli 2010

C# selective clone with a generic extension method

Hey guys, ever had to clone an object - but only duplicate the properties you actually needed. Or maybe you don't want to copy the id property... Something like that, well then take a look at this.

public static class ObjectExtensions
 public static T SelectiveClone(this Object obj, string[] properties)
  where T: new()
  T temp = new T();
  PropertyInfo[] propertyInfos = typeof(T).GetProperties();
  foreach (PropertyInfo pi in propertyInfos)
    pi.SetValue(temp, pi.GetValue(obj, null), null);

  return temp;

Well you can then do something like the following.
 Product is a class with the properties
 "title", "titleAlias", "subTitle", "description", 
 "price", "stock" and "id"
 "original" is an existing object of the class Product

// The following copies all properties except "id"
Product product = original.SelectiveClone(new string[] {
 "title", "titleAlias", "subTitle", "description", "price", "stock"

Keine Kommentare:

Kommentar veröffentlichen