more about generics

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
 
E

eric

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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top