'C# Func(T) not accepting ref type input parameter

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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SLaks
Solution 2 JaredPar