With the addition of the Tuple class in .net 4, I have been trying to decide if using them in my design is a bad choice or not. The way I see it, a Tuple can be a shortcut to writing a result class (I am sure there are other uses too).
So this:
public class ResultType
{
public string StringValue { get; set; }
public int IntValue { get; set; }
}
public ResultType GetAClassedValue()
{
//..Do Some Stuff
ResultType result = new ResultType { StringValue = "A String", IntValue = 2 };
return result;
}
Is equivalent to this:
public Tuple<string, int> GetATupledValue()
{
//...Do Some stuff
Tuple<string, int> result = new Tuple<string, int>("A String", 2);
return result;
}
So setting aside the possibility that I am missing the point of Tuples, is the example with a Tuple a bad design choice? To me it seems like less clutter, but not as self documenting and clean. Meaning that with the type ResultType
, it is very clear later on what each part of the class means but you have extra code to maintain. With the Tuple<string, int>
you will need to look up and figure out what each Item
represents, but you write and maintain less code.
Any experience you have had with this choice would be greatly appreciated.
Tuples are great if you control both creating and using them - you can maintain context, which is essential to understanding them.
On a public API, however, they are less effective. The consumer (not you) has to either guess or look up documentation, especially for things like Tuple<int, int>
.
I would use them for private/internal members, but use result classes for public/protected members.
This answer also has some info.