Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func / Action delegates with reference arguments/parameters or anonymous functions

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; } 
like image 209
user287107 Avatar asked Dec 17 '12 22:12

user287107


People also ask

Which type of delegate is func?

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.

What is the difference between Func and Action delegate?

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.

What is the use of Func delegate in C#?

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.

What are the differences between Func predicate action?

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).


2 Answers

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.

like image 117
dtb Avatar answered Oct 05 '22 14:10

dtb


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);
like image 38
Reed Copsey Avatar answered Oct 05 '22 15:10

Reed Copsey