0

If I have a custom date type called MyDate in which I have written operators for implicit conversion of double and MyDate to each other.

My question: is there any way to switch this implicit conversion off for a particular method parameter ? is that a good idea at all?

e.g.

public class A {
    ...

    public void AMethod(double x, double y) {

      // do something
    }
}

I don't want in the particular case of AMethod() for someone to be able to call it like this:

A a = new A();
a.AMethod(m, n);  // m and n are of type MyDate
3
  • How would you want them to call it? How do you use it?
    – Andrei V
    Feb 7, 2014 at 11:08
  • Why do you want to turn it off? I think you may be asking the wrong question.
    – dcastro
    Feb 7, 2014 at 11:12
  • @AndreiV only when m and n are double.
    – jambodev
    Feb 7, 2014 at 11:12

2 Answers 2

3

I don't think it is possible to switch off implicit conversions for selected methods only, either you get all of them or nothing.

Having said that, implicit conversions should only be implemented if you don't loose anything while doing the conversion, e.g. you should not care if the conversion occurred or not. If this is not the case (or if this is not the case in one direction at least), then change the implicit conversions to explicit and your issue with disappear. Of course your code will be more explicit with all these conversions, but rightly so.

2

It is not a good idea. When you create your custom implicit conversions you should implement it in such a way that it is applicable in all possible scenarios. The possibility to switch it off in certain scenarios would make the code harder to read and could potentially introduce bugs.

If you want to have the possibility to switch the conversion on and off you should simply implement the explicit conversion (which you can then apply when needed).

Your Answer

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

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