Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have code like this:
C#
private delegate string MyDelegate(int requiredParameter, int optionalParameter = -1);
private string MyMethod(int requiredParameter, int optionalParameter = -1)
{
    return "Some return value";
}


Which I then call like this:
C#
string s = (string)this.Invoke(new MyDelegate(MyMethod), new object[] { 10 });


Based on some questions I saw on StackOverflow, I think that what I'm trying to do is possible, but this last line throws a TargetParameterCountException with the message Parameter count mismatch.

Any idea why this happens? Can I make it work in some manner that is more elegant than overloading?
Posted

 
Share this answer
 
Comments
BotCar 19-Apr-12 4:53am    
This works fine, up to the point of invoking the delegate. Unfortunately, Invoke now returns null.
If you know which method you are calling then
C#
string s = (string)this.Invoke(new MyDelegate(MyMethod), new object[] { 10 });

is pointless just do
C#
string s = MyMethod(10);

However if your method is dynamic then it would be set somewhere like
C#
private MyDelegate _mydelegate;

public void SetDelegate(MyDelegate del)
{
   _mydelegate = del;
}

and you would call this by
C#
private void somemethod()
{
     string s = _del(10); //using the defined delegate
}
 
Share this answer
 
Comments
BotCar 19-Apr-12 4:55am    
It is done for thread safety. It is basically a way to force the method to be executed on the GUI thread.
Mehdi Gholam 19-Apr-12 5:05am    
Delegates are so you don't have to do this kind of reflection, and they are thread safe.
BotCar 19-Apr-12 5:32am    
Not true. As soon as I try executing the delegate without invoking it on the appropriate control, I get an InvalidOperationException telling me the cross-thread operation is not valid because the control can only be accessed from the thread it was created on.
Mehdi Gholam 19-Apr-12 9:16am    
You are probably updating UI controls in your delegate, and not doing computations.
BotCar 19-Apr-12 9:27am    
Yes. That's why I invoke the method on the UI thread.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900