A Beginner guide to using Tuples in C# Part 1

For folks starting out with little knowledge of Tuples in C#

·

2 min read

A Beginner guide to using Tuples in C# Part 1

Photo by Andrew Neel on Unsplash

Tuples are a very popular data structure in C#. It was first introduced in C# 4.0. Have you ever wanted to return multiple or more than one type from a method?

I'm pretty sure a lot of us have been there before. This use case is where Tuples shine. They help in returning multiple values from a method or function. One way you could possibly do this is using the out parameter but Tuples clear outshines it has it has some other useful functionalities which would be discuss in detail on the sequel of this article with useful code examples.

This is a very simplified guide to helping you start with Tuples so I wouldn't bore you with lots of talk. Let's get down to writing code.

Now we can simply use a Dictionary that has Key and Value pair to return 2 types from a method.

     public static Dictionary<string, int> GetUserDictionary()
    {
        Dictionary<string, int> users = new();
        result.Add(("Evans", 15));
        result.Add(("Sandra", 17));
        result.Add(("Paul", 19));
        result.Add(("Amina", 16));

        return users;
    }
    static void Main(string[] args)
    {
        var userDictionary = GetUserDictionary();
        foreach (var user in userDictionary)
        {
            Console.WriteLine($@"
            {user.Key} is {user.Value} years old.");
        }
    }

Impressive right?! But Tuples still outshines it. Now let's see a small glimpse of what tuples can do.

    private static List<(string name, int age, string location)> GetUserTuples()
    {
        List<(string name, int age, string location)> result = new();

        result.Add(("Evans", 15, "Lagos"));
        result.Add(("Sandra", 17, "Abuja"));
        result.Add(("Paul", 19, "Lagos"));
        result.Add(("Amina", 16, "UK"));

        return result;
    }
       var usersTuples = GetUserTuples();
        foreach (var user in usersTuples)
        {
            Console.WriteLine($@"
            {user.name} is {user.age} years old and lives in {user.location}");
        }

As you can see with Tuples you can return more than 2 different datatypes and more without any issues. You can return whatever type whether it be enum, int, float, decimal, double, boolean or custom data types.

Tuples make writing code a lot more easier and faster. You also don't need to worry too much about memory allocations as they are structs so they don't take up too much memory leaving less work for the GC while disposing resources.

On the next article. We would be checking the benchmarks on Tuples and Dictionaries to see which is faster and takes less memory.

Until the next time. Happy coding.