I just wondered, how the exact syntax is for ref
and out
parameters for delegates and inline lambda functions.
here is an example
if a function is defined as
public void DoSomething(int withValue) { }
a delegate in a function can be created by
public void f()
{
Action<int> f2 = DoSomething;
f2(3);
}
how is that syntax, if the original function would be defined as
public void DoSomething(ref int withValue) { withValue = 3; }
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter.
An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference). Predicate is a special kind of Func often used for comparisons (takes a generic parameter and returns bool).
You need to define a new delegate type for this method signature:
delegate void RefAction<in T>(ref T obj);
public void F()
{
RefAction<int> f2 = DoSomething;
int x = 0;
f2(ref x);
}
The reason why the .NET Framework does not include this type is probably because ref
parameters are not very common, and the number of needed types explodes if you add one delegate type for each possible combination.
You can't use Action
, Func<T>
, or the built-in delegates, but need to define your own in this case:
delegate void ActionByRef<T>(ref T value);
Then, given this, you can have:
int value = 3;
ActionByRef<int> f2 = DoSomething;
f2(ref value);
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