tags:

views:

132

answers:

2

Hello,

I have an instance of a class, I want to change an object data member of this instance only with another object of the same type (swap), due to my system constraints i can't use =,new or setter operators.

Basically I would like to change the value of a field of a variable, the field is an object contained inside another object - the variable which its instance I have.

is it possible using reflection? if so can someone please give me basic direction?

Thanks Yoav

+5  A: 

Yes, its possible.

In short, do something like

Type typeInQuestion = typeof(TypeHidingTheField);
FieldInfo field = typeInQuestion.GetField("FieldName", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(instanceOfObject, newValue);

to change the value of a hidden (private/protected/internal) field. Use the corresponding FieldInfo.GetValue(...) to read; combine the two trivially to get your desired swapping operation.

Don't hold me to the BindingFlags (I always seem to get those wrong on the first attempt) or the exact syntax, but that's basically it.

Look over System.Reflection for reference.

Kevin Montrose
BindingFlags look good but may also want to include Public... BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance
David Liddle
+1  A: 

If you use .NET 3.5, you can use my open-source library, Fasterflect, to address that with the following code:

typeof(MyType).SetField("MyField", anotherObject);

When using Fasterflect, you don't have to bother with the right BindingFlags specification and the performance implication (as when using reflection).

Buu Nguyen