Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit operator - when is it a good/bad idea?

Tags:

c#

implicit

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.

like image 370
Benjol Avatar asked Nov 23 '09 11:11

Benjol


2 Answers

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
like image 97
Vincent Robert Avatar answered Sep 17 '22 17:09

Vincent Robert


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 lose 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 lose some type checking in a way, the compiler is not going to prompt you with an error.

like image 42
Grzenio Avatar answered Sep 19 '22 17:09

Grzenio