Well, I need to repeat same code for many properties.
I've seen examples taking Action
delegates, but they don't fit quite well here.
I want something like this: (see explanation below)
Dictionary<Property, object> PropertyCorrectValues;
public bool CheckValue(Property P) { return P.Value == PropertyCorrectValues[P]; }
public void DoCorrection(Property P) { P.Value = PropertyCorrectValues[P]; }
.
I want to have a dictionary containing many properties and their respective "correct" values. (I know it's not well declared, but that's the idea). Properties are not necessarely inside my class, some of them are in objects of different assemblies.
A method bool CheckValue(Property)
. This method must access the actual value
of the property and compare to the correct value
.
And a method a void DoCorrection(Property)
. This one sets the property value
to the correct value.
Remember I have many of those properties, I wouldn't like to call the methods by hand for each property. I'd rather iterate through the dicionary in a foreach
statement.
So, the main question is in the title.
I've tried the
by ref
, but properties don't accept that.Am I obligated to use
reflection
??? Or is there another option (if I need, reflection answer will be accepted as well).Is there anyway I can make a dictionary with
pointers
in C#? Or some kind of assignment thatchanges the value of variable's target
instead ofchanging the target to another value
?
Thanks for the help.
In addition to Ben's code I'd like to contribute the following code fragment:
When using this "automatic" value correction you might also consider:
PropertyInfo
object just by knowing the property name and independently of the declaring class; that's why I chosestring
for the key.You can do this using reflection. Get a list of the properties on the object of interest with
typeof(Foo).GetProperties()
. YourPropertyCorrectValues
property can have typeIDictionary<PropertyInfo, object>
. Then use theGetValue
andSetValue
methods onPropertyInfo
to perform the desired operations: