How to return multiple values in C#?
Methods can return a value to the caller. If the return type (the type listed before the method name) is not
void
, the method can return the value by using the return
keyword. A statement with the return
keyword followed by a variable, constant, or expression that matches the return type will return that value to the method caller. Methods with a non-void return type are required to use the return
keyword to return a value. The return
keyword also stops the execution of the method.
If the return type is
void
, a return
statement without a value is still useful to stop the execution of the method. Without the return
keyword, the method will stop executing when it reaches the end of the code block.
Sometimes, you want your method to return more than a single value. Starting with C# 7.0, you can do this easily by using tuple types and tuple literals. The tuple type defines the data types of the tuple's elements. Tuple literals provide the actual values of the returned tuple.
In the following example,
(string, string, object, int)
defines the tuple type that is returned by the GetPersonalInfo
method. The expression (per.FirstName, per.MiddleName, per.Photo, per.Age)
is the tuple literal; the method returns the first, middle, and last name, along with the personal image, of a PersonInfo
object.
Lets get started !
Define the method with return types. Here you are passing personal data id value to retrieve the all the information and then return based on the data type mentioned
public (string, string, object, int) GetPersonalInfo(string id)
{
PersonInfo per = PersonInfo.RetrieveInfoById(id);
return (per.FirstName, per.MiddleName, per.Image, per.Age);
}
The caller can then consume the returned tuple with code like the following:
var person = GetPersonalInfo("853");
Console.WriteLine("{person.Item1} {person.Item3}: age = {person.Item4}");
Another way to define
Names can also be assigned to the tuple elements in the tuple type definition
public (string FName, string MName, object pImage, int Age) GetPersonalInfo(string id)
{
PersonInfo per = PersonInfo.RetrieveInfoById(id);
return (per.FirstName, per.MiddleName, per.Picture, per.Age);
}
var person = GetPersonalInfo("111111111");
Console.WriteLine("{person.FName} {person.LName}: age = {person.Age}");
0 Comments