Home > Blockchain >  Return multiple values from method
Return multiple values from method

Time:12-09

I want to return multiple values from my method ValidateAddress(). I know that I could create a new class which contains all the properties I need and return this class, but is it possible to directly return two values from a method?

ValidateAddress()

public void ValidateAddress(string address)
{
    if (string.Equals(address, "address"))
    {
        // return address and true
    }
    else
    {
        // return address and false
    }
} 

CodePudding user response:

If you want to return multiple types in one method, you can use tuples. In the method signature, you can use parenthesis to specify the types you want to return.

Example:

var result = ValidateAddress("address");
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);

(string, bool) ValidateAddress(string address)
{
    if (string.Equals(address, "address"))
    {
        return (address, true);
    }
    else
    {
        return (address, false);
    }
}

If you want to give a name to these values, there are two different ways. One way is to give a name to the types in the method signature.

Example:

var result = ValidateAddress("address");
Console.WriteLine(result.address);
Console.WriteLine(result.isValid);

(string address, bool isValid) ValidateAddress(string address)
{
    if (string.Equals(address, "address"))
    {
        return (address, true);
    }
    else
    {
        return (address, false);
    }
}

The second possibility is to create two local variables in the return.

Example:

(string address, bool isValid) = ValidateAddress("address");
Console.WriteLine(address);
Console.WriteLine(isValid);

(string, bool) ValidateAddress(string address)
{
    if (string.Equals(address, "address"))
    {
        return (address, true);
    }
    else
    {
        return (address, false);
    }
}

CodePudding user response:

You can:

public bool ValidateAddress(string address)
{
    return (string.Equals(address, "address"))
        ? true
        : false;
} 

You don't need to return address as you passed it in the first place :)

CodePudding user response:

You can return multiple values from a method by using the out keyword

public void ValidateAddress(out string address, out bool isValid)
{
    address = "";
    isValid = true;
}

You can call this method like this

string address;
bool isValid;

ValidateAddress(out address, out isValid);
  • Related