What is the best way to store pairs of strings, make an object or use a class in .NET?

Vidar picture Vidar · Aug 17, 2011 · Viewed 47.2k times · Source

Don't know whether I'm having a "thick day" - but I just wondered what is the best route here.

Context:

I have a list of fields and I want to store alias names with them (I'm using .NET 2.0 BTW) e.g.

enter image description here

So its essentially a pair of strings:

REFERENCE, Ref

COMMUNITY, Community

POST_CODE, Zip Code

... and I'm thinking it seems overboard all the time to keep creating objects for things like this, so should I create a StringDictionary and store the values that way, even though I would not use any of the functionality of the StringDictionary class and I'm not bothered about a key value pair association etc - I just want to keep a pair of strings essentially.

Any help/pointers would be great.

Answer

Blindy picture Blindy · Aug 17, 2011

The "pair" generic class for .NET is Tuple. You would use it like:

var strings=new List<Tuple<string, string>>();
strings.Add(Tuple.Create("REFERENCE", "Ref"));

A dictionary is a perfectly acceptable substitute if the left-most string is unique (ie a key). You'll get errors otherwise.

As to whether it's better to use the built-in collections or create an actual object, depends on your needs (will you be adding more columns later on? you can't do that with a dictionary approach), how often you use it (if it's a core type, you should probably make a domain model for it) etc.

Edit: As to not using any dictionary built-in functionality, that's not true: you're using its binary search algorithm and internal tree construction for lightning-fast look-ups. A list of either Tuple or your own type most likely won't have this and it will revert to a linear search.