G
Guest
I try to compare to values of generic value type T in a generic class as
follow:
public class C<T> where T : struct
{
private T value1;
private T value2;
C(T value1, T value2)
{
this.value1 = value1;
this.value2 = value2;
}
public void SomeMethod()
{
if (value1 != value2)
DoSomething();
}
}
and I got the following message at compile time :
"Operator '!=' cannot be applied to operands of type 'T' and 'T'"
Ok, I can use the following code :
if (value1.Equals(value2) == false)
DoSomething();
but doing so, I'm loosing all the advantage of generics
==> value1 and value2 are boxed before comparison occurs...
It was already the case for variable initialisation, I need to cast a value
to Object before it can be cast back to T (see : 12/29/2005 post "Generics
limitation on .Net") :
value1 = (T)(Object)Int32.MinValue;
since it was used once in my class, I didn't care about extra
boxing/unboxing operation.
But value1 vs value2 comparison occurs in a loop in real situation (I mean
in my real program) :
for (Int32 i = value1.Length; i-- != 0; i++)
{
if (value1 != value2)
DoSomething();
}
The question is : Does generics really usefull in such sitautions ?
follow:
public class C<T> where T : struct
{
private T value1;
private T value2;
C(T value1, T value2)
{
this.value1 = value1;
this.value2 = value2;
}
public void SomeMethod()
{
if (value1 != value2)
DoSomething();
}
}
and I got the following message at compile time :
"Operator '!=' cannot be applied to operands of type 'T' and 'T'"
Ok, I can use the following code :
if (value1.Equals(value2) == false)
DoSomething();
but doing so, I'm loosing all the advantage of generics
==> value1 and value2 are boxed before comparison occurs...
It was already the case for variable initialisation, I need to cast a value
to Object before it can be cast back to T (see : 12/29/2005 post "Generics
limitation on .Net") :
value1 = (T)(Object)Int32.MinValue;
since it was used once in my class, I didn't care about extra
boxing/unboxing operation.
But value1 vs value2 comparison occurs in a loop in real situation (I mean
in my real program) :
for (Int32 i = value1.Length; i-- != 0; i++)
{
if (value1 != value2)
DoSomething();
}
The question is : Does generics really usefull in such sitautions ?