How to return multiple values from a method?

Viewed 127

From the following code, I want y to return multiple values, but the program returns only the last one.

public int runDraw()
{
    for (int j = 1; j <= numberofDraws; j++)
    {
        ...
        if (even_count > odd_count)
        {
            Console.WriteLine("The result of {0} draw is Even.", j);
            y = 1;
        }
        else if (even_count < odd_count)
        {
            Console.WriteLine("The result of {0} draw is Odd.", j);
            y = 2;
        }
        else
        {
            Console.WriteLine("The result of {0} draw is Draw.", j);
            y = 3;
        }
    }
    return y;
}
3 Answers

One option would be to return an enumeration of int, as a single int cannot represent multiple values directly. Here's an example using yield return which will only bother continuing to the next value if you ever ask for it.

    public IEnumerable<int> runDraw()
    {
        for (int j = 1; j <= numberofDraws; j++)
        {
        ...
            if (even_count > odd_count)
            {
                Console.WriteLine("The result of {0} draw is Even.", j);
                yield return 1;
            }
            else if (even_count < odd_count)
            {
                Console.WriteLine("The result of {0} draw is Odd.", j);
                yield return 2;
            }
            else
            {
                Console.WriteLine("The result of {0} draw is Draw.", j);
                yield return 3;
            }
        }
        yield return y;
        // What you do here really depends on your unshared logic
        // You might return 0 or throw an exception if this is invalid
    }

You can then access the values iteratively, for example with a foreach loop:

foreach (int j in runDraw())
{
    Console.WriteLine(j);
}

you can achieve this via array or collection.

  1. Using array

     int[] result = new int[numberofDraws];
     result[j] = your result (1,2,3 based on condition)
     return result;
    
  2. Using List

     List<int> result = new List<int>();
     result.Add(1);
     return result;
    

Note: Change the return type as per usage in case you are going with an array use int[], if you are going with list use List<int>.

You can use out parameters or tuples for returning multiple values from any function, check for them.

Related