Using reflection to set an object property property

I have two classes.

public class Class1 { public string value {get;set;} } public class Class2 { public Class1 myClass1Object {get;set;} } 

I have an object of type Class2. I need to use reflection on Class2 to set the value ... property, i.e. if I were to do this without reflection, this is how I would do it:

 Class2 myObject = new Class2(); myObject.myClass1Object.value = "some value"; 

Is there a way to do this using reflection to access the property "myClass1Object.value"?

Thanks in advance.

+5
reflection
Sep 09 '09 at 10:30
source share
4 answers

In principle, it is divided into two accesses to properties. First you get the myClass1Object property, then you set the value property as a result.

Obviously, you will need to take any format in which you have the name of the property and separate it - for example. by points. For example, this should do an arbitrary depth of properties:

 public void SetProperty(object source, string property, object target) { string[] bits = property.Split('.'); for (int i=0; i < bits.Length - 1; i++) { PropertyInfo prop = source.GetType().GetProperty(bits[i]); source = prop.GetValue(source, null); } PropertyInfo propertyToSet = source.GetType() .GetProperty(bits[bits.Length-1]); propertyToSet.SetValue(source, target, null); } 

Admittedly, you'll probably want a little more error checking than this :)

+11
Sep 09 '09 at 22:33
source share

Try the library (Phantom: Easy reflection in .NET) , I think it can help you.

+1
Nov 13 '09 at 13:31
source share

I was looking for answers to the case when you need to get the value of a property when the property name is given, but the nesting level of the property is unknown.

Eg. if the input is "value" instead of providing the full name of the property, such as "myClass1Object.value".

Your answers inspired my recursive solution below:

 public static object GetPropertyValue(object source, string property) { PropertyInfo prop = source.GetType().GetProperty(property); if(prop == null) { foreach(PropertyInfo propertyMember in source.GetType().GetProperties()) { object newSource = propertyMember.GetValue(source, null); return GetPropertyValue(newSource, property); } } else { return prop.GetValue(source,null); } return null; } 
+1
Mar 28 '16 at 8:55
source share
  public static object GetNestedPropertyValue(object source, string property) { PropertyInfo prop = null; string[] props = property.Split('.'); for (int i = 0; i < props.Length; i++) { prop = source.GetType().GetProperty(props[i]); source = prop.GetValue(source, null); } return source; } 
0
Jun 27 '19 at 7:12
source share



All Articles