C# Tuple misuse
2 min readApr 2, 2024
Tuples are way to group multiple data elements in a lightweight data structure.
Mostly I saw its being used to return multiple values. What are other ways?
- Class->reference types
- Ref and Out variable-> “out” and “ref” parameters will not work with the async methods.
Benefits of tuples
- you can return multiple values
- Named values
- Tuples are lightweight
- support the == and != operators
- works with async methods
Then why am I against it?
When I was reviewing the code, I saw tuples being used everywhere.
- Long methods returning multiple values breaking Single responsibility principal.
- Same method retrieving data, applying business logic and returning status of each in form of tuples.
- Replacing class with tuple. Returning no. of values, where we can return class object. And in calling method we need to initializing object.
- Instead of writing separate method for separate purpose, saved time by writing just one.
- Problem came when client changed the requirement. The whole function need to be re-written. This time I intervened-> smaller coherent functions😉
Good Examples
If you need to quickly return a pair of coordinates it’s better to have something like this:
(double Latitude, double Longitude) getCoordinates()
{
return (144.93525, -98.356346);
}
Another example
List<(int X, int Y)> coordinates = new List<(int X, int Y)> { (0, 0), (3, 4), (7, 2) }; foreach (var (x, y) in coordinates) {
Console.WriteLine($”X: {x}, Y: {y}”);
}