Search code examples
c#funcoutout-parameters

C# - How can I pass a reference to a function that requires an out variable?


public class Foo
{
    public void DoFoo()
    {
       int x;
       var coll = TheFunc("bar", out x);
    }

    public Func<string, int, ICollection<string>> TheFunc { get; set; }
}

Error: "Argument 2 should not be passed with the 'out' keyword."

public class Foo
{
    public void DoFoo()
    {
       int x;
       var coll = TheFunc("bar", out x);
    }

    public Func<string, out int, ICollection<string>> TheFunc { get; set; }
}

Error: "Invalid variance modifier. Only interface and delegate type parameters can be specified as variant."

How do I get an out parameter in this function?


Solution

  • You need to make your own delegate:

    delegate ICollection<string> MyFunc(string x, out int y);