more about generics

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hi!

I'm reading in abook and it says the following.
However, attempting to compare the two arguments op1 and op2 below fails to
compile

Public bool Compare(T1 op1, T2 op2)
{
if (op1 == op2)
{
return true;
}
else
{
return false;
}
}

The reson for this is that this code assumens that T1 supports the ==
operator

Can somebody explain why this will not compile and how do I do if I want to
compare op1 to op2 for equality ?

//Tony
 
Hi!

I'm reading in abook and it says the following.
However, attempting to compare the two arguments op1 and op2 below fails to
compile

Public bool Compare(T1 op1, T2 op2)
{
      if (op1 == op2)
      {
           return true;
      }
      else
      {
            return false;
       }

}

The reson for this is that this code assumens that T1 supports the ==
operator

Can somebody explain why this will not compile and how do I do if I want to
compare op1 to op2 for equality ?

//Tony

You can't use "a == b" if a and b don't have the same type.
To compare a and b, i'll use the equals method inherited from Object.
Probably something like that :

Public bool Compare(T1 op1, T2 op2)
{
return op1.equals(op2);
}
 
Back
Top