Posted By

kdrucker on 08/07/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Update domain object properties using .NET Reflection.


 / Published in: C#
 

Since your domain object is passed in as a ref parameter, it cannot be cast to object, you must box it prior to calling the method. The caller of the method must also ensure that the System.Type of the value parameter matches the type expected by the property being updated.

  1. ExampleClass example = new ExampleClass();
  2.  
  3. object oExampleContainer = example;
  4. updateObjectProperty(ref oExampleContainer, "exampleProperty", 12345, new List<string>());
  5.  
  6. private void updateObjectProperty(ref object thisObject, string propertyName, object value, List<string> excludeList)
  7. {
  8. if (!excludeList.Contains(propertyName))
  9. {
  10. if (thisObject != null)
  11. {
  12. Type thisType = thisObject.GetType();
  13. PropertyInfo[] propertyInfos = thisType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  14. foreach (PropertyInfo info in propertyInfos)
  15. {
  16. if (info.Name.ToUpper() == propertyName.ToUpper())
  17. {
  18. info.SetValue(thisObject, value, null);
  19. break;
  20. }
  21. }
  22. }
  23. }
  24. }

Report this snippet  

You need to login to post a comment.