I have a method with an out
parameter, and I'd like to point an Action
or Func
(or other kind of delegate) at it.
This works fine:
static void Func(int a, int b) { } Action<int,int> action = Func;
However this doesn't
static void OutFunc(out int a, out int b) { a = b = 0; } Action<out int, out int> action = OutFunc; // loads of compile errors
This is probably a duplicate, but searching for 'out parameter' isn't particularly fruitful.
Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.
Calling a method with an out argument In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32. TryParse method, which attempts to convert a string to a number.
The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition as well as in the calling method.
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values.
Action and Func specifically do not take out or ref parameters. However, they are just delegates.
You can make a custom delegate type that does take an out parameter, and use it, though.
For example, the following works:
class Program { static void OutFunc(out int a, out int b) { a = b = 0; } public delegate void OutAction<T1,T2>(out T1 a, out T2 b); static void Main(string[] args) { OutAction<int, int> action = OutFunc; int a = 3, b = 5; Console.WriteLine("{0}/{1}",a,b); action(out a, out b); Console.WriteLine("{0}/{1}", a, b); Console.ReadKey(); } }
This prints out:
3/5 0/0
No, not with the builtin delegates. out
and ref
are special qualifiers and the delegate has to be setup with them explicitly since they are completely different calling styles.
However, if you defined your own delegate, you can do this:
delegate void OutAction<T1, T2>(out T1 a, out T2 b);
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