Implicit statement - when is this a good / bad idea?

I am working on an application in which the concept of direction (forward / backward) is very important.

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

To try to put 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. } 

Now I am 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 are there any classic gotchas that I probably get.

+4
source share
2 answers

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

A classic getcha with implicit conversions is when people implement it in such a way that they lose some information during the conversion, which leads to a general mess, as you can imagine (for example, things that should be equal are no longer equal, etc. etc.), but in your example this is not so.

The only thing you need to be careful with is that you somehow lose some type checking, the compiler will not offer you an error.

+4
source

In principle, implicit conversion is always a bad idea when developing standard libraries. Because, if you suddenly find a case when you are implicit conversion breaks, you can not easily fix it, because so many people depend on it.

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

And if you find one case when it breaks:

  • you will learn something (which is always nice)
  • you can back off and fix the code
+6
source

All Articles