I recently discovered you can use an implicit operator (TYPENAME) to make implicit conversions happen automatically for your custom types in C#:

public class Vector
{

  public static implicit operator string( Vector v )
  {
    return v.ToString() ;
  }

}

Now you can

Vector v = new Vector();
Console.WriteLine( v ) ;

Instead of

Vector v = new Vector();
Console.WriteLine( v.ToString() ) ;

So, at first I thought, WOW! That’s great. I’m developing a Matrix and Vector class together and its nice to be able to convert the Vector to a System.Drawing.PointF automatically, so instead of defining a property like:

public class Vector
{

  public System.Drawing.PointF PointF{ get {
    return new System.Drawing.PointF( this.x, this.y ) ;
  } }

}

For use in

Vector v = new Vector( 5, 7 ) ;
graphics.FillEllipse( v.PointF, 10 ) ;

I can now:

public class Vector
{

  public static implicit operator System.Drawing.PointF( Vector v )
  {
    return new System.Drawing.PointF( v.x, v.y ) ;
  }

}

So we could actually

Vector v = new Vector( 5, 7 ) ;
graphics.FillEllipse( v, 10 ) ;  // IMPLICIT TYPE CONVERSION
// TO POINTF NOW SUPPORTED!!

So that’s nice.

BUT.

What’s NOT NICE is what the compiler does when you define an implicit operator THAT ALSO has the == operator DEFINED FOR IT, but your class does not.

So, guess what happens if I DON’T define operator== for my Vector class, but I have the implicit operator string defined as shown above?

GUESS WHAT HAPPENS???

Vector v1 = new Vector( 5, 7 );
Vector v2 = new Vector( 5, 7 ) ;
if( v1 == v2 )  // v1 AND v2 ARE CONVERTED TO STRINGS, THEN COMPARED!!
{
}

This is AWFUL!! Instead of the compiler flagging it now, with “operator not defined for type Vector” (as it would have if we didn’t define implicit operator string), the compiler merrily compiles it!

THIS IS BAD!! Not even mentioning efficiency, in my ToString() method, there’s a round off leaving only 2 decimals! This means that 2.581 and 2.589999 are EQUAL in my program right now!!

Bad! BAD .NET!! BAD!!!!!!!!

Post a Comment