
Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
> teel,
>
[quoted text clipped - 5 lines]
> There isn't really much benefit here to using generics here, since the
> constraint system pretty much prevents you from doing what you want.
Actually for this case, generics work very well. Constrain the type T to
implement IComparable, and then use IComparable.CompareTo instead of <,=,>
It's with actual math (+, -, *, /, etc) that generics don't work -- at all!
>> Hi there,
>> I'm trying to apply "less than" and "more than" operators on the
[quoted text clipped - 80 lines]
>> private T m_MaxValue;
>> }
teel - 26 Sep 2007 23:46 GMT
> Actually for this case, generics work very well. Constrain the type T to
> implement IComparable, and then use IComparable.CompareTo instead of <,=,>
> It's with actual math (+, -, *, /, etc) that generics don't work -- at all!
Thanks a lot both of you guys!!
It's working with the IComparable :)
Best regards,
teel
Michael S - 27 Sep 2007 08:58 GMT
> Actually for this case, generics work very well. Constrain the type T to
> implement IComparable, and then use IComparable.CompareTo instead of <,=,>
Nice brainwork. I thought the problem was unsolvable.
I had never thought of using IComparable.
- Michael Starberg
teel - 27 Sep 2007 18:39 GMT
Ok guys, may I ask you another question? My final Parameter class
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>();
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 explain why the MyEnum which actually consists of a
primitive type objects is not IComparable? If it stores only int
values it is comparable. What I am doing wrong? What topic should I
get familiar with?
Best regards,
teel
Ben Voigt [C++ MVP] - 27 Sep 2007 23:20 GMT
> Ok guys, may I ask you another question? My final Parameter class
> looks like this:
answered in your new post