The Daily Parker

Politics, Weather, Photography, and the Dog

K is for Key-Value Pairs

Blogging A to ZThe Blogging A-to-Z challenge continues on Day 11 with key-value pairs and simple tuples.

A tuple is a finite ordered list of elements. In mathematics, you usually see them surrounded by parentheses and delineated with commas, like so: (2, 3, 5, 8, 13).

.NET has several generic Tuple classes with 2 through 7 items in the sequence, plus a KeyValuePair<TKey, TValue> structure that is the equivalent of Tuple<T1, T2>.

I'm actually not a fan of the Tuple class, though I get why it exists. I prefer naming things what they actually are or do. If you're doing mathematics and need a 3-item tuple, use Tuple<T1, T2, T3>. But if you're doing geography and you need a terrestrial coordinate, create an actual Node<Easting, Northing, Altitude> class and use that instead. (Or just add the Inner Drive Extensible Architecture from NuGet to your project and use mine.)

You probably can't avoid the KeyValuePair<TKey, TValue> structure, however. It's coupled to the Dictionary<TKey, TValue> class, which you will probably use frequently.

Example:

#region Copyright ©2018 Inner Drive Technology

using System.Collections.Generic;

#endregion

namespace InnerDrive.DailyParkerAtoZ.WeekOne
{
	public class KeyValuePairs
	{
		public void Add(string name, Room room)
		{
			_rooms.Add(name, room);
		}

		public Room Find(string name)
		{
			return _rooms.ContainsKey(name) ? _rooms[name] : null;
		}

		public void Remove(string name)
		{
			if (_rooms.ContainsKey(name)) _rooms.Remove(name);
		}
		
		private readonly Dictionary<string, Room> _rooms = new Dictionary<string, Room>();
	}
}

Under the hood, the Dictionary<string, Room> object uses KeyValuePair<string, Room> objects to give you a list of rooms. Note that the key must be unique inside the dictionary; you can't have two rooms called "cupboard under the stairs" or it will throw an exception. Also note the safety features in the code above: the demo class won't throw an exception if you try to find or remove a room that doesn't exist. (There's a philosophical question buried in there: why should or shouldn't it throw?)

As always, download and play with the code samples for more fun and enjoyment.

Add comment

Loading