# 從 C# 中的函式返回多個值

## 使用 C# 中的陣列從函式中返回多個值

``````using System;

namespace return_multipe_values {
class Program {
public static int[] compare(int a, int b) {
int[] arr = new int[2];
if (a > b) {
arr[0] = b;
arr[1] = a;
} else {
arr[0] = a;
arr[1] = b;
}
return arr;
}
static void Main(string[] args) {
int[] returnvalue = Program.compare(10, 12);
Console.WriteLine("Smaller Value = {0}", returnvalue[0]);
Console.WriteLine("Larger Value = {0}", returnvalue[1]);
}
}
}
``````

``````Smaller Value = 10
Larger Value = 12
``````

## 使用 C# 中的帶有結構體/類物件的函式返回多個值

``````using System;

namespace return_multipe_values {
struct Values {
public int x;
public int y;
}

class Program {
public static Values comparevalues(int a, int b) {
Values V = new Values();
if (a > b) {
V.x = b;
V.y = a;
} else {
V.x = a;
V.y = b;
}
return V;
}
static void Main(string[] args) {
Values returnedvalues = Program.comparevalues(10, 12);
Console.WriteLine("Smaller Value = {0}", returnedvalues.x);
Console.WriteLine("Larger Value = {0}", returnedvalues.y);
}
}
}
``````

``````Smaller Value = 10
Larger Value = 12
``````

``````using System;
public class Sample {
int x;
int y;
public void setxy(int v, int u) {
x = v;
y = u;
}
public void getxy() {
Console.WriteLine("The smaller value = {0}", x);
Console.WriteLine("The greater value = {0}", y);
}
}
public class Program {
public static Sample compare(int a, int b) {
Sample s = new Sample();
if (a > b) {
s.setxy(b, a);
} else {
s.setxy(a, b);
}
return s;
}
public static void Main() {
Sample returnedobj = Program.compare(10, 12);
returnedobj.getxy();
}
}
``````

``````The smaller value = 10
The greater value = 12
``````

## 在 C# 中使用 `Tuples<T1,T2>` 類從函式返回多個值

``````using System;

public class Program {
public static Tuple<string, string, int> ReturnMultipleValues() {
var result = Tuple.Create<string, string, int>("value1", "value2", 3);
return result;
}
public static void Main() {
var returnedvalues = ReturnMultipleValues();
Console.WriteLine(returnedvalues);
}
}
``````

``````(value1, value2, 3)
``````

## 在 C# 中使用 `(T1,T2)` 表示法從函式中返回多個值

``````using System;

public class Program {
public static (string, string, int) ReturnMultipleValues() {
return ("value1", "value2", 3);
;
}
public static void Main() {
(string val1, string val2, int val3) = ReturnMultipleValues();
Console.WriteLine("{0} {1} {2}", val1, val2, val3);
}
}
``````

``````value1 value2 3
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.