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
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
While C and C++ may sound similar, their features and usage differ. C is a procedural programming language that support objects and classes. On the other hand C++ is an enhanced version of C programming with object-oriented programming support.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With