Tuple Class – C#

Tuple class

With tuple class (available from version .Net 4.0) our function can return more then one value. I’ll show you on a simple example.

Imagine that we want to return cars with brand and model but the type of car is common to all these cars.

Let’s see, we’ve got three cars – Audi A4, Mitsubishi Lancer and Mazda RX-8. All of these is passenger car. Instead of add additional propertion to our DTO class represent cars. We can create it as follows.

Class represent Brand.

public class Brand
{
    public string Name { get; set; }
    public string Model { get; set; }
}

And class Cars, which returns cars including their type.

class Cars
{
    public Tuple<string,List<Brand>> GetTheCars()
    {
        List<Brand> list = new List<Brand>()
        {
            new Brand()
            {
                Name = "Audi",
                Model = "A4"
            },
            new Brand()
            {
                Name = "Mitsubishi",
                Model = "Lancer"
            },
            new Brand()
            {
                Name = "Mazda",
                Model = "RX-8"
            }
        };
        return new Tuple<string, List<Brand>>("Passenger car", list);
    }
}

Now we can display all of these cars.

class Program
{
    static void Main(string[] args)
    {
        Cars cars = new Cars();
        var model = cars.GetTheCars();
        foreach (var item in model.Item2)
        {
            Console.WriteLine($"{item.Name} {item.Model} is a {model.Item1}");
        }
        Console.ReadKey();
    }
}

As you can see, we specify the parameters in the order in our case item1 is the car type and item2 is the class representing the brand. To appeal to a type car we don’t need to iterate through the collection.

tuple

Summary

The class tuple should apply only in some specific situations.Of course you will decide when and if, you will use this at all. In addition, this class is immutable.

tuple

Link to the project.

Leave a Reply

Your email address will not be published. Required fields are marked *