Yesterday’s post was just a quick test of the csharpformat web page kindly provided by Jean-Claude Manoli on his web site. The code was an excerpt from a noddy little class that I happened to create that day. It was just a convenience class that allowed three objects to be combined and used as a lookup key into a Dictionary. The actual scenario was a cache for PerformanceCounter instances that needed to be looked up based on the combination of a category name, performance counter name and instance name. I actually did search for an existing .NET triple class in the framework and found the System.Web.UI.Triplet class. Unfortunately it was associated with a web assembly rather than a more general purpose assembly. In addition it didn’t override the Equals and GetHashCode methods so couldn’t be used as a key in a hashtable/dictionary.
This is an example of a class where I question whether the fields shouldn’t be made public since it is only a convenience class and direct access to the fields is convenient depending on the context it is used in. Fortunately there were benefits in making the class immutable so I didn’t have to face the encapsulation quandary. The class ended up being placed into the Torq.Foundation.Tool namespace so it can be used by code in a variety of contexts. Consideration was given to making it a generic class but getting the programmer to type Triplet<string, string, string> triplet = new Triplet<string, string, string>(); was just so way overboard given its typical expected usage as a key.
public class Triplet
{
private object first;
private object second;
private object third;
public Triplet( object first, object second, object third )
{
this.first = first;
this.second = second;
this.third = third;
}
public object First
{
get { return first; }
}
public object Second
{
get { return second; }
}
public object Third
{
get { return third; }
}
public override bool Equals( object obj )
{
Triplet triplet = obj as Triplet;
if ( triplet == null ) return false;
return Equals( first, triplet.first ) && Equals( Second, triplet.Second ) &&
Equals( Third, triplet.Third );
}
public override int GetHashCode()
{
return GetHashCode( first ) ^ GetHashCode( second ) ^ GetHashCode( third );
}
private int GetHashCode( object obj )
{
return obj != null ? obj.GetHashCode() : 0;
}
}