开发者

Tuple or out parameter for multiple return values?

开发者 https://www.devze.com 2023-02-25 13:00 出处:网络
I want to return multiple parameter from a method in c#.I just wanted to know which one is better out or Tuple?

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 lastNa开发者_JAVA技巧me)
{
    int i = name.LastIndexOf (' ');
    firstNames = name.Substring (0, i);
    lastName   = name.Substring (i + 1);
}


static Tuple<string,string> Split (string name)
{
//TODO
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消