How to return multiple values from a method in C#

As a developer how many times you may have wondered that wish I could return at least two values, instead of creating a object, from a method just the way we could return a single value.

Before, we jump into the solution, we can look at different ways we can return multiple values as we know currently.

  1. Create a class, and return the object of that class type.
  2. Pass the out parameters, and assign those variables in the method.
  3. Pass a ref object and assign the values in the method.
  4. Declare the Global variables (class level variables), and can be access anywhere.

Now the curiosity poses to know that what is the another way beside above options.

We can use Tuple keyword to achieve returning multiple values from the method as we see in the below example.

public static void Main(string[] args)
{
    int userId = 0;
    Tuple<string, string> userData = GetUserData(userId);
}

public static Tuple<string, string> GetUserData(int userId)
{
    return new Tuple<string, string>("Hello", "World");
}

The first question comes to our mind that we can as well create a class or struct and return it, but sometimes it is inconvenient to create class or struct all the time.

Link to Further reading

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s