tags:

views:

67

answers:

2

I'm working on an application where the notion of Direction (forwards/backwards) is very important.

The problem is that spread throughout the code base there are several different conventions: in some places it is true/false, and in others +1/-1.

To try and bring this together, I created:

public class DirectionClass
{ 
     public bool Forwards { get; set; }
     public double Sign { get; set; }
     public EDirection { get; set; }
     //plus associated constructor overloads, implementing IEquatable, etc.
}

I'm now wondering if implicit conversions would be a good or bad idea:

public static implicit operator DirectionClass(double sign);
public static implicit operator DirectionClass(bool forwards); //etc..

and whether there are classic gotchas which I am likely to encouter.

+2  A: 

In general you should be fine with implicit conversions in this case.

The classic gotcha with implicit conversions is when people implement it in a way that they loose some information during conversion, which results in an overall mess as you can imagine (e.g. things that should be equal are not equal anymore, etc.). But this is not the case in your example.

The only thing you have to be careful with is that you loose some type checking in a way, the compiler is not going to prompt you with an error.

Grzenio
+2  A: 

Basically, implicit conversion is always a bad idea when designing standard libraries. Because if you suddenly discover a case where you implicit conversion breaks, you cannot fix it easily because so much people depend on it.

On the other hand, if you are responsible for the whole code base (or at least your team). Just go for what makes your life(s) simpler.

And if you discover one case where it breaks:

  • you will have learned something (which is always nice)
  • you can step back and fix the code
Vincent Robert