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

2

5
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?

Romans answered 22/7, 2011 at 20:19 Comment(2)
see #1366189 for some detailsDelastre
FYI the more general rule here is that a type argument must be a type which is convertible to object. "out int" is not convertible to object; you cannot convert "reference to an int variable" to object.Triturate
M
7

You need to make your own delegate:

delegate ICollection<string> MyFunc(string x, out int y);
Maclaine answered 22/7, 2011 at 20:20 Comment(0)
J
8

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; }
}
Jesus answered 22/7, 2011 at 20:21 Comment(0)
M
7

You need to make your own delegate:

delegate ICollection<string> MyFunc(string x, out int y);
Maclaine answered 22/7, 2011 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.