9

I know I can avoid boxing by adding my own Equals implementation.

public struct TwoDoubles
{
    public double m_Re;
    public double m_Im;

    public TwoDoubles(double one, double two)
    {
        m_Re = one;
        m_Im = two;
    }

    public override bool Equals(object ob)
    {
           return Equals((TwoDoubles)ob);
    }
    public bool Equals(TwoDoubles ob)
    {
        TwoDoubles c = ob;
        return m_Re == c.m_Re && m_Im == c.m_Im;
    }
}

I can't call this an override as much as an overload. By the magic of the runtime it does correctly call the correct Equals() implementation based on the type of the caller.

Why can't I override and change the parameter type to TwoDoubles and let boxing occur by the power of the runtime on an as needed basis? Is it because C# doesn't support parameter contravariance (if that's the reason then why is it not supported...seems a small step from object o = new TwoDoubles())?

UPDATE
Clarification: object is a part of the inheritance hierarchy of a struct. Why can we not specify a more derived type as a parameter to override an implementation from a less derived type? This would allow us to write:

 public override bool Equals(TwoDoubles ob)
 {
        TwoDoubles c = ob;
        return m_Re == c.m_Re && m_Im == c.m_Im;    
 }

Which should be called when the variable is a TwoDouble even if said variable has been boxed into an object type.

6
  • 1
    This will throw exception if ob is not TwoDoubles in the override function. And it makes not sense to check the type in the other one.
    – Magnus
    Apr 30, 2012 at 21:28
  • 1
    @Magnus - fixed. An oversight as i was rushing out the door Apr 30, 2012 at 21:43
  • 4
    Just so you are aware, since you override the Equals(object) method, you should also override the GetHashCode() method as well. Apr 30, 2012 at 21:57
  • @Magnus - how could the situation for an exception ever arise? Isnt it impossible for any non-twodoubles variable to call Equals on twodoubles? Apr 30, 2012 at 22:12
  • With your changes to the question it cant.
    – Magnus
    Apr 30, 2012 at 22:15

3 Answers 3

13

Why can't I override and change the parameter type to TwoDoubles?

Because that would not be typesafe!

class B
{
  public virtual void M(Animal animal) { ... }
}
class D : B
{
  public override void M(Giraffe animal) { ... }
}

B b = new D();
b.M(new Tiger());

And now you just passed a tiger to a method that actually only takes a giraffe!

Same thing in your case. You're overriding a method that takes any object with a method that can only take a struct; that's not typesafe.

Is it because C# doesn't support parameter type contravariance?

No, it is because you are asking for parameter type covariance, which is not typesafe.

C# does not support parameter type contravariance either, but that's not what you're asking for.

5
  • In your blog you explain that it is the projection that is covarient/contravarient/invarient, not the type. What is the projection in this case? blogs.msdn.com/b/ericlippert/archive/2009/11/30/… May 1, 2012 at 17:13
  • 2
    @P.Brian.Mackey: Good question! Consider the relation "method with parameter type X may legally override method with parameter type Y" and the relation "type Y is assignment compatible with type X". If the first relation holds every time the second relation holds then the first relation is contravariant in the parameter type. More precisely: the projection is the projection from "type T" to "a method with parameter type T", and it is this projection which is contravariant with respect to those two relations. May 1, 2012 at 18:15
  • 1
    @P.Brian.Mackey: To be a bit more formal: suppose we have a relation R1 on a set T; that is, a function R1(T, T)-->bool. Suppose we have a relation R2 on a set M, R2(M, M)-->bool. And suppose we have a projection P which is P(T)-->M. If R1(x, y) being true implies that R2(P(y), P(x)) is also true then P is contravariant. In this case R1 is "assignment compatibility of types", R2 is "legality of one method overriding another", and P is "take a type and make a method that has a parameter of that type". May 1, 2012 at 18:25
  • Forgive my ignorance, doesnt the formal proof reinforce the idea that we are dealing with contravarience rather than covarience? If yes, does the type safety problem still apply? May 1, 2012 at 22:41
  • 2
    @P.Brian.Mackey: That wasn't a proof, that was a more precise definition of contravariance. If your question is "would virtual method overriding with parameter type contravariance be typesafe?" the answer is yes, it would be typesafe. It's just not supported by the CLR or C#. (Or, for that matter, C++.) C# supports two kinds of parameter type contravariance; first, contravariance of generic delegate type conversions, and second, contravariance of parameter types when converting method groups to delegate types. Both require the varying types to be reference types. May 1, 2012 at 22:49
2

You can change the parameter (overload) for Equals, just as you've done, and boxing will occur as needed (i.e. whenever Equals(object) is called)

Because everything inherits (or implicitly via boxing) from object, you cannot stop people from being able to use Equals(object) on your type. However, by doing so, you get a boxed call.

If you are in control of the calling code, then always use your new overloaded option, i.e. Equals(TwoDouble)

Note, as one commentor already said, your code is slightly incorrect, do this instead:

public override bool Equals(object ob)
{
  if (ob is TwoDoubles)
    return Equals((TwoDoubles)ob);
  else
    return false;
}
public bool Equals(TwoDoubles c)
{
  return m_Re == c.m_Re && m_Im == c.m_Im;
}

EDIT as has been wisely suggested, you should accomplish this same task but by using the IEquatable interface, in this case IEquatable<TwoDouble> (note, no code change necessary from what we've done as it matches the signature)

3
  • 1
    The cast on the second Equals is not really necessary.
    – digEmAll
    Apr 30, 2012 at 21:39
  • 6
    I would suggest implementing the IEquatable<T> interface if you want a generic Equals method.
    – Magnus
    Apr 30, 2012 at 21:40
  • This repairs an implementation problem. For that ty, question updated. It doesnt address my question. Apr 30, 2012 at 21:58
2

If it worked as you suggested, where public override bool Equals(TwoDoubles c) { return m_Re == c.m_Re && m_Im == c.m_Im; } was all that was necessary to override the Equals(object) method, what would this code do?

TwoDoubles td = new TwoDoubles();
object o = td;
bool b = o.Equals(new object()); // Equals(object) overridden with Equals(TwoDouble)

What should happen on line 3?

  • Should it call Equals(TwoDouble)? If so, with what parameter? A default TwoDouble with all zeros? That'd violate the rules surrounding equality.
  • Should it throw a cast exception? We followed the method signature properly, so that shouldn't happen.
  • Should it always return false? Now the compiler has to be aware of what the Equals method means, and will have to treat it differently than other methods.

There's no good way to implement this, and it quickly causes more problems than it solves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.