Reputation: 77
in my application that uses reflection i have two classes
public class FirstClass
{
public string someVar;
public SecondClass second;
public FirstClass()
{
second = new SecondClass();
}
}
public class SecondClass
{
public string anotherVar;
}
in my main program i have an instance of FirstClass
MainProgram()
{
Object obj = InstanceOfFirstClass() // reflected instance of first class
}
How do i set the value of anotherVar inside obj?
Upvotes: 2
Views: 3255
Reputation: 40838
With public fields, this is relatively simple:
object obj = InstanceOfFirstClass();
object second = obj.GetType().GetField("second").GetValue(obj);
second.GetType().GetField("anotherVar").SetValue(second, "newValue");
If the fields were not public, then you would need to use an overload of GetField
that takes a BindingFlags
argument with the NonPublic
flag set.
In .Net 4, you could just use dynamic
:
dynamic obj = InstanceOfFirstClass();
obj.second.anotherVar = "newValue";
Upvotes: 2
Reputation: 609
You can find the example which reads the field and set a value of the field via reflection in http://msdn.microsoft.com/en-us/library/6z33zd7h.aspx. In your case it will look like
Object myObject = InstanceOfFirstClass() // reflected instance of first class
Type myType = typeof(FirstClass);
FieldInfo myFieldInfo = myType.GetField("second",
BindingFlags.Public | BindingFlags.Instance);
// Change the field value using the SetValue method.
myFieldInfo.SetValue(myObject , //myobject is the reflected instance
value);//value is the object which u want to assign to the field);
Upvotes: 1