I am just begining to explore the basic of using generics and would have thought i could implement this simple pattern to solve a typical problem in my daily use. I have spent days searching for a simple example. I can find examples for looking for .Equals, but not much past that. I want to be able to instantiate with things like:
Spec<double> voltageSpec;
Spec<int> cyclesSpec;
Spec<myClass> fishInTheOceanSpec;
then be able to :
bool isGood = voltageSpec.inSpec(5.0);
bool isGood cyclesSpec.inSpec(2);
bool isGood fishInTheOceanSpec.( new myClass(20));
My attempt is shown below.
/// <summary>
/// Generic object to hold a specification i.e min and max limits.
/// Implements a method to determin if a value is between limits.
/// </summary>
public class Spec<T> : IComparer<T>
{
public Spec()
{
Min = default(T);
Max = default(T);
}
public T Min { get; set; }
public T Max { get; set; }
public bool inSpec(T Value)
{
if ((Comparer<T>.Default.Compare(Value, this.Max) <= 0) &
(Comparer<T>.Default.Compare(Value, this.Min) >= 0))
return true;
else
return false;
}
public int Compare(T x, T y)
{
if (x == y) return 0;
if (x < y) return -1;
if (x > y) return 1;
}
public Spec<T> Copy()
{
return (Spec<T>)this.MemberwiseClone();
}
}
I would refactor as follows – make
Tbe responsible to provide the comparison – this works already for primitive types, your custom classes just have to implementIComparable<T>: