Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
michael Avatar asked Jul 22 '11 20:07

michael


2 Answers

Define a delegate type:

public delegate ICollection<string> FooDelegate(string a, out int b);

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

    public FooDelegate TheFunc { get; set; }
}
like image 143
cdhowie Avatar answered Nov 02 '22 23:11

cdhowie


You need to make your own delegate:

delegate ICollection<string> MyFunc(string x, out int y);
like image 33
SLaks Avatar answered Nov 03 '22 00:11

SLaks