Tech Off Post

Single Post Permalink

View Thread: Tuple type
  • User profile image

    I actually developed my own tuple library in 2.0 that I've used for a few years, which ended up being very similar to what's coming in 4.0, so I'm actually in an oddly appropriate place to comment on this.  Smiley


    Tuples fit very nicely between concrete property classes and anonymous types in their degree of formality.  Like concrete classes, and unlike anonymous types, they can be easily returned from methods.  Like anonymous types, and unlike concrete classes, they are very simple to create and maintain.  (Anyone who has ever had to implement the whole Equals/GetHashCode/op_Equality/op_Inequality thing knows what I mean... ugh.)


    Tuples are great as quick and easy keys for dictionaries stored in class fields.  For example, let's say you needed a field in your class that would allow fast lookup of someone by name and favorite color.   (Ok, that's a little arbitrary, but pretend it's some multi-value key you didn't want to have to write and maintain a whole internal class for.)  


    Currently, you would need to do something along the lines of:


    private Dictionary<string, Dictionary<Color, Person>> nameAndFaveColorLookup;


    which isn't very fun to write code against, and doesn't programmatically scale very easily to adding multiple keys.


    Alternatively, you could do:


    private Dictionary<NameAndFavoriteColor, Person> nameAndFaveColorLookup;

    private struct NameAndFavoriteColor : IEquatable<NameAndFavoriteColor>
    	//... insert properties and equality gunk here ...


    which also isn't very fun because you have to maintain a bunch of equality stuff that's tedious and error prone, and is a lot of gruntwork for a simple lookup.


    With tuples, you could create a class field like:


    private Dictionary<Tuple<string,Color>,Person> nameAndFaveColorLookup;


    and be done.