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

I just wondered how the exact syntax for the ref and out parameters is for delegates and built-in lambda functions.

here is an example

if the function is defined as

  public void DoSomething(int withValue) { } 

delegate in function can be created

  public void f() { Action<int> f2 = DoSomething; f2(3); } 

like this syntax if the original function is defined as

  public void DoSomething(ref int withValue) { withValue = 3; } 
+7
source share
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 the .NET Framework does not include this type is probably because ref parameters are not very common, and the number of required types explodes if you add one delegate type for each possible combination.

+12
source

You cannot use Action , Func<T> or built-in delegates, but in this case you need to define your own:

 delegate void ActionByRef<T>(ref T value); 

Then, given this, you can:

 int value = 3; ActionByRef<int> f2 = DoSomething; f2(ref value); 
+4
source

All Articles