SoFunction
Updated on 2025-03-06

Summary of the implementation method of returning multiple values ​​in C#

Preface

Usually a method can only return one value, but if at some point, we want to return multiple values, for example, a method will split a floating point number into an integer and a decimal number.

In C#), the function method wants to return multiple values, and the method and sample code implemented through tuples, lists, arrays, classes, structures and out parameters.

Implementation method

1. Use tuples to return multiple values ​​(ValueTuple and Tuple)

1) Implementation using ValueTuple

ValueTupleNamed Tuples (available in C# 7.1), the advantage is that it is the simplest, immutable and easy to construct.

private (double first, double second) GetHeight()
{
   return (1,2);
}
var result = GetHeight();
($"{}, {}");
var (first, second) = GetHeight();
($"{first}, {second}");

2) Implementation using Tuple

The .NET Framework already has a common Tuple class. However, these classes have two main limitations. First, the Tuple class names its properties Item1, Item2, and so on. These names contain no semantic information. Using these tuple types does not achieve the meaning of each attribute. The new language feature allows you to declare and use semantically meaningful names for elements in tuples.

public Tuple<int, int> ViaClassicTuple()
{
   return new Tuple<int, int>(1,2);
}
var tuple = ViaClassicTuple();
($"{tuple.Item1}, {tuple.Item2}");

2. Use list (list<T>) or array to return multiple values

1) Use List to implement

private List<double> GetHeight()
{
   return new List<double>(){1,2};
}
var result = GetHeight();
($"{result[0]}, {result[1]}");

2) Implement using arrays

private double[] GetHeight()
{
      return new double[2]{ 1,2};
}
var result = GetHeight();
($"{result[0]}, {result[1]}");

3. Use a class or structure to return multiple values

1) Use class implementation

public class SomeClass
{
   public int First { get; set; }
   public int Second { get; set; }
   public SomeClass(int first, int second)
   {
      First = first;
      Second = second;
   }
}
public SomeClass ViaSomeClass()
{
   return new SomeClass(1, 2);
}
var someClass = ViaSomeClass();
($"{}, {}");

2) Implement using structure

public struct ClassicStruct
{
   public int First { get; set; }
   public int Second { get; set; }
   public ClassicStruct(int first, int second)
   {
      First = first;
      Second = second;
   }
}
public ClassicStruct ViaClassicStruct()
{
   return new ClassicStruct(1, 2);
}
var classicStruct = ViaClassicStruct();
($"{}, {}");

4. Use out parameters to implement

Any operation performed by the parameter is performed on the independent variable. Just likerefThe keyword is the same, except that ref requires that variables be initialized before passing them. It is also similar to the in keyword, except that in does not allow the invoked method to modify the parameter value. To useoutParameters, method definitions, and calling methods must all use the out keyword explicitly.

1) Multiple out parameters implementation

public bool ViaOutParams(out int first, out int second)
{
   first = 1;
   second = 2;
   return someCondition;
}
if(ViaOutParams(out var firstInt, out var secondInt))
   ($"{firstInt}, {secondInt}");

2) Implementation using out ValueTuple

public bool ViaOutTuple(out (int first,int second) output)
{
   output = (1, 2);
   return someCondition;
}
if (ViaOutTuple(out var output))
   ($"{}, {}");

Use the out keyword.

Demo1:

using System;
 
namespace test
{
    class Testout
    {
        public int getParts(double n, out double frac)
        {
            int whole;
 
            whole = (int)n;
 
            frac = n - whole; //pass fractional part back through frac            return whole;     //return integer portion Return the integer part        }
    }
 
    class Useout
    {
        static void Main()
        {
            Testout Tout = new Testout();
 
            int i;
            double f;
 
            i = (1234.56789, out f);
 
            ("Integer Part:" + i);
            ("Decimal Part:{0:#.###}" , f);
            ("Decimal Part:" + f);
            ();// Listen to keyboard events and press any key to exit        }
    }
}

Demo2:

  /// &lt;summary&gt;
    /// Ping command to detect whether the network is smooth    /// &lt;/summary&gt;
    /// <param name="urls">URL data</param>    /// <param name="errorCount">Number of connection failures during ping</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static bool MyPing(string[] urls, out int errorCount)
    {
        bool isconnected = true;
         ping = new ();
        errorCount = 0;
        try
        {
            PingReply pr;
            for (int i = 0; i &lt; ; i++)
            {
                pr = (urls[i]);
                if ( != )
                {
                    isconnected = false;
                    errorCount++;
                    ("Target server{0}Unreachable,Error counterrorCount={1}", urls[i], errorCount);
                }
                // ("Ping " + urls[i] + "    " + ());
                ("Ping " + urls[i] + "    " + ());
            }
        }
        catch
        {
            isconnected = false;
            errorCount = ;
        }
        //if (errorCount &gt; 0 &amp;&amp; errorCount &lt; 3)
        //  isconn = true;
        return isconnected;
    }
 
 
 
 
/// &lt;summary&gt;
    /// Detect network connection status    /// &lt;/summary&gt;
    /// &lt;param name="urls"&gt;&lt;/param&gt;
    //public static void CheckServeStatus(string[] urls)
    public bool CheckNetStatus(string[] urls)
    {
 
        int errCount = 0;//The number of connection failed during ping 
        //if (!LocalConnectionStatus())
        //{
        // ("Network exception~no connection");        //}
        if (!MyPing(urls, out errCount))
        {
            if ((double)errCount /  &gt;= 0.3)
            {
                ("Network connection exception");
                return false;
                //("Network exception~no response to connections");            }
            else
            {
                ("Network connection is normal");
                return true;
            }
        }
        else
        {
                ("Network connection is normal");
            return true;
            //("Network is normal");        }
    }

This is the article about the implementation method of returning multiple values ​​in C#. For more related contents of returning multiple values ​​in C#, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!