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 c
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.
in vb with generics, but rudimentary error handling:
Module somereflectionops
Function GetFieldValue(Of OBTYPE, FIELDTYPE)(instance As OBTYPE, fieldname As String, Optional specbindingflags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance) As FIELDTYPE
Dim ot As Type = GetType(OBTYPE)
Dim fi As FieldInfo
Try
fi = ot.GetField(fieldname, BindingFlags.Default Or specbindingflags)
If fi Is Nothing Then Return Nothing
Return fi.GetValue(instance)
Catch ex As Exception
Return Nothing
End Try
End Function
Function SetFieldValue(Of OBTYPE, FIELDTYPE)(instance As OBTYPE, fieldname As String, value As FIELDTYPE, Optional specbindingflags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance) As Boolean
Dim ot As Type = GetType(OBTYPE)
Dim fi As FieldInfo
Try
fi = ot.GetField(fieldname, BindingFlags.Default Or specbindingflags)
If fi Is Nothing Then Return false
fi.SetValue(instance, value)
Return True
Catch ex As Exception
Return False
End Try
End Function
End Module
use: SetFieldValue(Of cartonclass, Integer)(cartonyoudropped, "survivingeggcount", 3)
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).