Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent implicit casting in functions?

Tags:

c#

I am writing an Utility class which has methods like IsEquals and IsGreaterThanEquals that accept arguments of type double. When I send the float values to the methods they are implicitly converted to double and compared. I don't want this to happen. How to make sure float values are not implicitly converted to double and possibly throw compilation error when I send float type values instead of double type values?

public static bool Equals(double firstDouble, double secondDouble)
{
     return Math.Abs(firstDouble - secondDouble) <= double.Epsilon;
}

The above code works even if I pass float parameter values. I would like the compilation to throw error when I pass float parameter values to above method.

like image 532
Sam Avatar asked Apr 08 '26 19:04

Sam


1 Answers

If you want an error during compilation, provide the methods with float's, but mark them as Obsolete:

    [Obsolete("Don't use floats", error: true)]
    public static bool Equals(float a, float b) {
        throw new NotImplementedException();
    }

    [Obsolete("Don't use floats", error: true)]
    public static bool Equals(double a, float b) {
        throw new NotImplementedException();
    }

    [Obsolete("Don't use floats", error: true)]
    public static bool Equals(float a, double b) {
        throw new NotImplementedException();
    }

    public static bool Equals(double firstDouble, double secondDouble) {
        return Math.Abs(firstDouble - secondDouble) <= double.Epsilon;
    }
like image 124
GvS Avatar answered Apr 10 '26 09:04

GvS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!