Click here to Skip to main content
15,867,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Does anyone know how Control.Invoke can invoke a method which has ref
parameters?

For example,

C#
class A {
public delegate MyFuncHandler(ref int i, ref int j);

public void MyFunc(ref int i, ref int j)
{
..
}

public A

public void MyCaller(DataGridView oDataGridView)
{
int x = 1;
int y = 1;

...

oDataGridView.Invoke(new MyHandler(MyFunc), new object { ref x, ref y });

....
}

oDataGridView.Invoke(new MyHandler(MyFunc), new object { ref x, ref y });


produces compilation error. Am I doing this wrong, or Control.Invoke does
not allow method with ref parameters?

Thanks
Posted
Updated 27-Sep-13 22:51pm
v2

1 solution

The overload of Control.Invoke has an overload with a params object array. The params parameter allows to pass a variable number of elements directly without the need to explicitly pack them into an array.
In params, you cannot pass references. But keep in mind that if you pass reference types, that they are by definition reference paramater. I.e. whatever you modify inside the invocation has an effect to the passed reference type parameters.

Assuming you have instances of reference types (not value types) that you pass to the invocation, your call looks like this:
C#
oDataGridView.Invoke(new MyHandler(MyFunc), x, y);

or even
C#
oDataGridView.Invoke(MyFunc, x, y);

On the other hand, if you need to pass multiple value types values as references, you can pack them into some kind of container and pass the container (which is a reference type) to the handler. If it's homogenous types (all the same type), use any of the collections from System.Collections.Generic namespace. If it is inhomogenous types (not all types are the same), use a Tuple or create your own specific argument class (e.g. like a class derived from EventArg like the ones used in EventHandlers).

Cheers
Andi
 
Share this answer
 
v3
Comments
xuyunhai 28-Sep-13 6:18am    
System.Windows.Forms.Control.Invoke()
seem have only two overload method.
one is none params,the other is explicitly pack them into an array.
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.control.invoke(v=vs.85).aspx
Andreas Gieriet 28-Sep-13 16:06pm    
Yes, that's what I say: it has a params array. See what params mean (http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.100).aspx). Checkout also the difference between refeence type and value type - or maybe more useful comparison: C# Concepts: Value vs Reference Types.
Cheers
Andi

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