Returning two values, Tuple vs 'out' vs 'struct'

前端 未结 6 1188
傲寒
傲寒 2020-12-24 04:23

Consider a function which returns two values. We can write:

// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple

        
6条回答
  •  抹茶落季
    2020-12-24 04:58

    Adding to the previous answers, C# 7 brings value type tuples, unlike System.Tuple that is a reference type and also offer improved semantics.

    You can still leave them unnamed and use the .Item* syntax:

    (string, string, int) getPerson()
    {
        return ("John", "Doe", 42);
    }
    
    var person = getPerson();
    person.Item1; //John
    person.Item2; //Doe
    person.Item3;   //42
    

    But what is really powerful about this new feature is the ability to have named tuples. So we could rewrite the above like this:

    (string FirstName, string LastName, int Age) getPerson()
    {
        return ("John", "Doe", 42);
    }
    
    var person = getPerson();
    person.FirstName; //John
    person.LastName; //Doe
    person.Age;   //42
    

    Destructuring is also supported:

    (string firstName, string lastName, int age) = getPerson()

提交回复
热议问题