How to return multiple values ​​from a function in C #

    3 answers 3

    In versions C # c 4 to 6 inclusive, the best options to return from the function (or rather, the method) were the return of the Tuple <> tuple or the creation of a class \ structure with the desired properties. The variant with out-parameters is worse, since a little out of the main paradigms used in the development of C #, and was built rather to support the import of native functions.

    Today (C # 7) a convenient and sufficiently high-quality alternative is to use tuples supported at the syntax level of a language using the value type ValueTuple (True, you need to add the System.ValueTuple library, for example through NuGet).

    return tuple tuple <>

    public Tuple<string, int> GetVasya() { return Tuple.Create("Вася", 16); } 

    class creation

     class Person { public string Name {get;set;} public int Age {get;set;} } ... public Person GetVasya() { return new Person { Name = "Вася", Age = 16 }; } 

    use ValueTuple

     public (string Name, int Age) GetVasya() { return ("Вася", 16); } 
    • Nevertheless, just in C # 7, out-parameters were rebirth due to the out var construction. - Pavel Mayorov
    • @PavelMayorov + deconstructors - Andrew NOP

    In order to return several values ​​from a function, you need to declare the necessary parameters with out modifiers. For example.

      class SomeClass { public int getManyData(out object outData1, out object outData2) { // Код функции outData1 = someValue1; // Необходимо инициализировать выходной параметр outData2 = someValue2; // Необходимо инициализировать выходной параметр return result; } } 

      Return Tuple <>

        Protected by a member Pavel Mayorov on Sep 1 '16 at 11:38 .

        Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

        Maybe you want to answer one of the unanswered questions ?