Hi there!
I've got a Parameter (any parameter you can imagine) class used to
store a value. It has minValue, maxValue and the current value.
Parameter can be float, bool, integer and should also be enum. It
looks like this:
public class Parameter<T> where T : IComparable<T>
{
public Parameter(T value, T minValue, T maxValue)
{
m_Value = value;
m_MinValue = minValue;
m_MaxValue = maxValue;
}
public T Value
{
get { return m_Value; }
set
{
if (m_MinValue.CompareTo(value) > 0)
m_Value = m_MinValue;
else if (m_MaxValue.CompareTo(value) < 0)
m_Value = m_MaxValue;
else
m_Value = value;
}
}
private T m_Value;
private T m_MinValue;
private T m_MaxValue;
}
And it's working perfectly for int and float types. But when I try to
create an object:
Parameter<MyEnum> obj = new Parameter<MyEnum>();
where:
MyEnum : int {A, B, C;}
I get an error:
The type 'MyEnum' must be convertible to 'System.IComparable<MyEnum>'
in order to use it as parameter 'T' in the generic type or method
'Parameter<T>'.
Could you please explain to me why the MyEnum which actually consists
of a
primitive type objects is not IComparable? If the Parameter stores
only int
values it is comparable, the same to float and I guess any numeric
type. What I am doing wrong? What topic should I get familiar with?
Best regards,
teel
teel - 27 Sep 2007 23:07 GMT
Ok, done. T should be IComparable not IComparable<T>
Best regards,
teel
Ben Voigt [C++ MVP] - 27 Sep 2007 23:19 GMT
> Hi there!
> I've got a Parameter (any parameter you can imagine) class used to
[quoted text clipped - 46 lines]
> values it is comparable, the same to float and I guess any numeric
> type. What I am doing wrong? What topic should I get familiar with?
I think that enum types only support the non-generic IComparable interface.
You could also get rid of the IComparable requirement and use
Comparer<T>.DefaultComparer, this will automatically pick the IComparable
implementation if it is available (but it is likely to be quite a bit
slower).
> Best regards,
> teel