0

Would it be possible to assign a method with out parameters to a Func<T1, T2> method parameter?

An example method I could use as parameter:

public string HelloMethod(out bool success)
{
    success = true;
    return "Hello";
};

The reason I want to do this is that I call a library where many (but not all) methods have out parameters with error codes and I want create a method to wrap the calls to the library with try catch log etc:

private TResult MakeLibraryCall(...func...) // what signature?
{
    try
    {
        return func(...); // unclear how to make call with out parameter
    }
    catch(Exception error)
    {
        Log(error);
    }

    return default;
}

Further I'm not sure how this would be called. I hope for something like:

var greeting = MakeLibraryCall((out success) => HelloMetod(out success));

Console.WriteLine(greeting) // => Hello
Console.WriteLine(success) // => true

Any help appreciated!

mortb
  • 9,361
  • 3
  • 26
  • 44
  • Does this answer your question? [Func with out parameter](https://stackoverflow.com/questions/1283127/funct-with-out-parameter) – Ahmed Yousif Jan 05 '21 at 15:56
  • @AhmedYousif: not sure how I would implement that delegate pattern in my code? It might work, but I don't know how to write the solution. – mortb Jan 05 '21 at 15:58
  • you can check my answer it enough to achieve what you want to do – Ahmed Yousif Jan 05 '21 at 16:35

1 Answers1

2

According to Microsoft Doc Built-in Delegate Func<T,TResult> its input parameter is not defined as out parameter

public delegate TResult Func<in T,out TResult>(T arg);

So you should define your custom delegate as follows:

delegate T MyDelegate<T,TInput>(out TInput input);

Then make it a prameter to your MakeLibraryCall function as follows:

private string MakeLibraryCall(MyDelegate<string,bool> func) 
{
    try
    {
        bool x = true;
        return func(out x); 
    }
    catch(Exception e)
    {
        //Log(error);
    }

    return default;
}

after that call the function MakeLibraryCall as follows:

public string HelloMethod(out bool success)
{
    success = true;
    return "Hello";
};

var greeting = MakeLibraryCall(HelloMethod);

if you want to out the parameter of func from MakeLibraryCall so you have to define it as out parameter of it as follows:

private string MakeLibraryCall(MyDelegate<string,bool> func, out bool success) 
    {
        try
        {
            return func(out success);  
        }
        catch(Exception e)
        {
            //Log(error);
            success = false;
        }
    
        return default;
    }

var success = false;
var greeting = MakeLibraryCall(HelloMethod,out success);
Ahmed Yousif
  • 2,298
  • 1
  • 11
  • 17