C# Returning & Getting Multiple Values from functions

C# Returning & Getting Multiple Values from functions

Returning multiple values isn't as hard as it used to be.

Introduction

In many cases, it can be useful to return multiple values from a function. For example, a function to get the first and last name of an User Class could return two string values.

Returning Multiple Values

To return multiple values, the easiest way is to use the () symbols in the return statement.

Example on it's own:

return (var1, var2)

Example in a method:

public static (string, string) FullName()
{
    string one = "Hello";
    string two = "World!";

    return (one, two);
}

Getting The Multiple Values From A Function Call

When calling the function, use parenthesis to get both the values. Make sure to remember to include the types.

(string f, string l) = User.FullName();

You can then use the values later.