5

Can Func<...> accept arguments passed by reference in C#?

static void Main()
{
    Func<string,int, int> method = Work;
    method.BeginInvoke("test",0, Done, method);
    // ...
    //
}
static int Work(ref string s,int a) { return s.Length; }
static void Done(IAsyncResult cookie)
{
    var target = (Func<string, int>)cookie.AsyncState;
    int result = target.EndInvoke(cookie);
    Console.WriteLine("String length is: " + result);
}

I am not able define a Func<...> which can accept the ref input parameter.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
abcd
  • 91
  • 1
  • 6

2 Answers2

7

The Func<T> delegates cannot take ref parameters.
You need to create your own delegate type which takes ref parameters.

However, you shouldn't be using ref here in the first place.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • For .NET 4 usage...see [this example for using `ref` parameter with `in` and `out` parameters](http://stackoverflow.com/a/24044772/175679). – SliverNinja - MSFT Jun 04 '14 at 18:23
5

Expanding on SLaks answers.

The Func<T> family of delegates are generic and allow you to customize the type of the arguments and returns. While ref contributes to C#`s type system it's not actually a type at the CLR level: it's a storage location modifier. Hence it's not possible to use a generic instantiation to control whether or not a particular location is ref or not.

If this was possible it would be very easy to produce completely invalid code. Consider the following

T Method<T>() {
  T local = ...;
  ...
  return local;
}

Now consider what happens if the developer called Method<ref int>(). It would produce both a local and return value which are ref. This would result in invalid C# code.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454