views:

452

answers:

2

I've got two classes.

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

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

I've got an object of type Class2. I need to use reflection on Class2 to set the value property... i.e, if I were doing it without reflection, this is how I would go about it:

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

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

Thanks in advance.

+3  A: 

Basically split it into two property accesses. First you get the myClass1Object property, then you set the value property on the result.

Obviously you'll need to take whatever format you've got the property name in and split it out - e.g. by dots. 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[bit.Length-1]);
    propertyToSet.SetValue(source, target, null);
}

Admittedly you'll probably want a bit more error checking than that :)

Jon Skeet
Very nice. I had ventured down that road already trying to get the PropertyInfo of the first Property, but I ran into a wall when I tried to call SetValue because I didn't actually have the source (i.e, you supplied the missing piece with the GetValue). Thanks!
Chu
Very useful! Thanks!
Jagd
+1  A: 

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

Wagner Andrade