5
Reply

Can you return multiple values from a function in C#?

Rajeev Kumar

Rajeev Kumar

1y
2.8k
0
Reply

Can you return multiple values from a function in C#?

    Returning multiple values from a function is not possible.
    Using some other features offered by C#, we can return multiple values to the caller method.
    This post provides an overview of some of the available alternatives to accomplish this.

    We can use the ref keyword to return a value to the caller by reference. We can use it to return multiple values from a method

    1. using System;
    2. public class Example
    3. {
    4. private static void fun(ref int x, ref int y)
    5. {
    6. x = 1;
    7. y = 2;
    8. }
    9. public static void Main()
    10. {
    11. int x = 0;
    12. int y = 0;
    13. fun(ref x, ref y);
    14. Console.WriteLine("x = {0}, y = {1}", x, y);
    15. }
    16. }
    17. /*
    18. Output: x = 1, y = 2
    19. */

    The out keyword causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed

    1. using System;
    2. public class Example
    3. {
    4. private static void fun(out int x, out int y)
    5. {
    6. x = 1;
    7. y = 2;
    8. }
    9. public static void Main()
    10. {
    11. int x = 0;
    12. int y = 0;
    13. fun(out x, out y);
    14. Console.WriteLine("x = {0}, y = {1}", x, y);
    15. }
    16. }
    17. /*
    18. Output: x = 1, y = 2
    19. */

    Yes, its possible

    As you use as tuple type.

    1. private static (int, string) func(int input){
    2. return (input, "sample string");
    3. }
    4. public static void Main() {
    5. var (index, text) = func(1);
    6. Console.WriteLine($"index= {index}, text= {text}");
    7. }

    Yes we can pass using out parameters in the method

    Yes