C# Tuple misuse

shalini Pahwa
2 min readApr 2, 2024
Sharing values of different types

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?

  1. Class->reference types
  2. Ref and Out variable-> “out” and “ref” parameters will not work with the async methods.

Benefits of tuples

  1. you can return multiple values
  2. Named values
  3. Tuples are lightweight
  4. support the == and != operators
  5. works with async methods

Then why am I against it?

When I was reviewing the code, I saw tuples being used everywhere.

  1. Long methods returning multiple values breaking Single responsibility principal.
  2. Same method retrieving data, applying business logic and returning status of each in form of tuples.
  3. Replacing class with tuple. Returning no. of values, where we can return class object. And in calling method we need to initializing object.
  4. Instead of writing separate method for separate purpose, saved time by writing just one.
  5. 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 of coordinates

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}”);

}

References

--

--