Loading...

return more than one value from a c sharp method using tuples

Published
05-01-2021

Often, in a C-sharp program there is a need to return more than one value from a method. For example, if you add a record to a database you might want to return a string value with a success message and an int value with the new record id value.

The long way is to add an object to your project that contains those two properties, and return an instance of that object from your method. The problem with this approach of course is that it adds bloat to the code base and if you have to do it a lot you end up with a lot of objects that are used once or twice.

We have all done it this way but there is a better way which has been around since C# 7.3.

The better way is to return a tuple. If you have the following Class:

public static class DemoClass{
  public static (string, double, int) TupleMethod(string inputStr, double inputDouble)
{
string retString = "Hello " + inputStr;
double retDouble = 1000 * inputDouble; return (retString, retDouble, 17);
}
}

You can use it as follows:

public class Program
{
    static void Main(string[] args)
    {
        //use a tuple to create values on the fly
        var (retString, retDouble, retInt) = DemoClass.TupleMethod("World", 17.94);
        Console.WriteLine(retString + " " + retDouble);

        //use existing values
        string myString;
        double myDouble;
        int myInt;

        (myString, myDouble, myInt) = DemoClass.TupleMethod("World", 17.94);
        Console.WriteLine(myString + " " + myDouble + " " + myInt);
    }
}

Since Test Driven Development is so popular nowadays, I have used a TDD approach and created a Test project first and then the demo code which you can download here


Latest posts