C# – When to Use a 2-Property Class Over KeyValuePair

ccoding-style

When should you put Key/Value type of data in it's own class instead of using a pre-built generic structure, such as a KeyValuePair or a Tuple?

For example, most ComboBoxes I create contain a DisplayName and a Value. This is the kind of data I am trying to decide when to put in a new class, and when to just use a KeyValuePair.

I am currently working on something that uses iCalendar, and the selected user's data ultimately gets combined into a key1=value1;key2=value2; type of string. I started out by putting the data in a KeyValuePair<string,string>, but now I am wondering if that should be it's own class instead.

Overall, I am interested in finding out what guidelines are used when deciding to use an existing structure/class like a KeyValuePair over a 2-property object, and in what kind of situations you would use one over another.

Best Answer

I'd generally use an object rather than a KeyValuePair or Tuple in most cases. First, when you come in 6 months later to make changes, it is alot easier to figure out what your intent was earlier rather than wondering what Tuple t is and why it has those funny values. Second, as things grow and change you can easily give your simple data transfer objects behavior as required. Need to have two name formats? Easy, just add appropriate ToString() overloads. Need it to implement some interface? No problem. Finally, there really is nearly zero overhead to creating a simple object, especially with automatic properties and code completion.

Bonus Protip: if you want to keep these objects from polluting your namespace, making private classes inside of classes is a great way to keep things under wraps and prevent strange dependencies.

Related Topic