1

How can out string values with Task function in C# i need fix this code to return Task with out string values

public Task<bool> DelUserTemp(string UserID, int FingerIndex ,out string result)
{
    return Task.Run(() =>
    {
        if (true)
        {
            result = "done";
            return true;
        }
        else
        {
            result = "error";
            return false;
        }
    });
}

2 Answers2

6

An alternative to using ref/out would be to return C# 7.0 tuples instead.

public Task<(bool Worked, string Result)> DelUserTemp(string UserID, int FingerIndex)
{
    return Task.Run(() =>
    {
        if (true)
        {
            return (true, "done");
        }
        else
        {
            return (false, "error");
        }
    });
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Magnus
  • 45,362
  • 8
  • 80
  • 118
1

Yet another example is to create class and return it:

public class MyResult
{
    public bool Succeeded {get;}
    public string ErrorMessage {get;}

    public MyResult(bool succeeded, string errorMessage)
    {
        Succeeded = succeeded;
        ErrorMessage = errorMessage;
    }
}

public Task<MyResult> DelUserTemp(string UserID, int FingerIndex ,out string result)
{
    return Task.Run(() =>
    {
        if (true)
        {
            return new MyResult(true, "done");
        }
        else
        {
            return new MyResult(false, "error");
        }
    });
}
Johnny
  • 8,939
  • 2
  • 28
  • 33