I’m tring to build a library for simplifing late binding calls in C#, and I’m getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call
public IInvoker AddParameter(ref object value) { //List<object> _parameters = new List<object>(); _parameters.Add(value); //List<bool> _isRef = new List<bool>(); _isRef.Add(true); return this; }
And that doesn’t work with value types, because they get boxed as an object, thus they are not modified. E.g:
int param1 = 2; object paramObj = param1; //MulFiveRef method multiplies the integer passed as a reference parameter by 5: //void MulFiveRef(ref int value) { value *= 5; } fi.Method('MulFiveRef').AddParameter(ref paramObj);
That doesn’t work. The late binding call is successful, and the inner List which holds the parameteres (_parameters ) does get modified, but not the value outside the call.
Does anyone knows a simple way to overcome this limitation? The AddParameter signature cannot be modified, as with late binding calls, you cannot know in advance the Type of the parameters (and either way you insert all the parameters for a call inside an object array prior to making the call)
Thanks in advance.
If the value is changing inside the method, you will need to declare a temp (
object) variable to pass (ref) to the method, and unbox it yourself afterwards:Note that this will not allow you to update the value after the event. Something like an event or callback might be an alternative way of passing changes back to the caller.
Note also that C# 4.0 has some tricks to help with this only in the context of COM calls (where
ref objectis so common [plus of coursedynamicfor late binding, as Jon notes]).