Victor Santos
Victor Santos

Reputation: 350

What is the best way to implement a method with 2 returns?

Quite often I come across some code where I have to return a boolean to indicate whether the method finished successfully or not and a string with an error message in case of a problem.

I've implemented this in two ways. The first consists in a class of response and all methods of all classes use this response class to communicate. Example:

public class ReturnValue {
    public bool Ok;
    public string Msg;
    public object SomeData;

    public ReturnValue() {
        this.Ok = true;
        this.Msg = null;
    }

    public ReturnValue(string Msg) {
        this.Ok = true;
        this.Msg = Msg;
    }

    public ReturnValue(object SomeData) {
        this.Ok = true;
        this.SomeData = SomeData;
    }

    public ReturnValue(bool Ok, string Msg) {
        this.Ok = Ok;
        this.Msg = Msg;
    }

    public ReturnValue(bool Ok, string Msg, object SomeData) {
        this.Ok = Ok;
        this.Msg = Msg;
        this.SomeData = SomeData;
    }
}

public class Test {
    public ReturnValue DoSomething() {
        if (true) {
            return new ReturnValue();
        } else {
            return new ReturnValue(false, "Something went wrong.");
        }
    }
}

The second way is to have a method that stores the message in case of error and to see the message simply call this method. Example:

public class Test {
    public string ReturnValue { get; protected set; }

    public bool DoSomething() {
        ReturnValue = "";

        if (true) {
            return true;
        } else {
            ReturnValue = "Something went wrong.";
            return false;
        }
    }
}

There is a right way to do this?

Upvotes: 2

Views: 96

Answers (2)

Servy
Servy

Reputation: 203820

Rather than relying on a return value to know if something succeeded, or what the error was if it didn't, C# generally relies on exceptions instead. If your program works, don't throw an exception. If it didn't work, throw an exception and include the error message in the exception thrown.

Upvotes: 3

Brad M
Brad M

Reputation: 7898

Personally, I prefer to use the ref keyword.

public bool DoSomething(ref string returnValue) {
    returnValue = "something";
    return true;
} 


string returnValue = "";
DoSomething(ref returnValue);
// returnValue now has new value.

Upvotes: 0

Related Questions