Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple or out parameter for multiple return values?

Tags:

c#-4.0

I want to return multiple parameter from a method in c#.I just wanted to know which one is better out or Tuple?

static void Split (string name, out string firstNames, out string lastName)
{
    int i = name.LastIndexOf (' ');
    firstNames = name.Substring (0, i);
    lastName   = name.Substring (i + 1);
}


static Tuple<string,string> Split (string name)
{
//TODO
}
like image 621
santosh singh Avatar asked Apr 13 '11 18:04

santosh singh


2 Answers

There is usually a (value) class hiding somewhere if you need to return more than one value from a method. How about a value class with the Split() method as ctor:

public class Name
{
    public Name(string name)
    {
        int i = name.LastIndexOf (' ');
        FirstNames = name.Substring (0, i);
        LastName   = name.Substring (i + 1);
    }

    public string FirstName {get; private set;}
    public string LastName {get; private set;}
}

Instead of

Split(name, out string firstName, out string lastName);

just do

Name n = new Name(name);

and access the first and last name via n.FirstName and n.LastName.

like image 91
EricSchaefer Avatar answered Sep 28 '22 18:09

EricSchaefer


Though this is a necro I would like to add that, given the new features in C#9 and C#10, the tuple approach is more intuitive and takes advantage of anonymous types. Sometimes classes are just overkill - especially if this function is an extension method.

You can now use this signature syntax for tuples:

public (T1, T2, T3, .... TN) MyMethod(your parameters)

And also pre-name tuple entries: (Using your example)

static (string firstName, string LastName) Split (string name)
{ 
   int i = name.LastIndexOf (' ');
   return (name.Substring (0, i), name.Substring (i + 1));
}

If you'd like, you can also fill the result tuple data into existing variables:

string name = "Cat Dog";
string firstName, lastName;
(firstName, lastName) = Split(name);
/// firstName = Cat, lastName = Dog

Either of these implementations is very readable, maintainable, and modular - since you don't need to define a class.

My personal preference is that you should only define a class if there is an internal object state or necessary methods needed for the data - otherwise use a tuple.

like image 37
dreamstep Avatar answered Sep 28 '22 19:09

dreamstep