Update domain object properties using .NET Reflection.


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.