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

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

By Rajeev Kumar in .NET on Jun 22 2023
  • Mayooran Navamany
    Jun, 2023 24

    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. */

    • 1
  • Cr Bhargavi
    Aug, 2023 30

    Yes, its possible

    • 0
  • Michael Hoang
    Jul, 2023 5

    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. }

    • 0
  • Mounika Bonasu
    Jun, 2023 29

    Yes we can pass using out parameters in the method

    • 0
  • Prafull Chauhan
    Jun, 2023 28

    Yes

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS