Adriano Di Giovanni
Adriano Di Giovanni

Reputation: 1515

Custom C# compiler warnings

If I try to perform an implicit conversion from double to int I get * a warning in the editor * a compilation error

enter image description here

How can I implement this behavior for operators of custom types?

public struct A
{
    private readonly double value;

    public A(double value)
    {
        this.value = value;
    }

    // NOTE I want this operation to be prohibited
    public static A operator +(A a, B b)
    {
        throw new InvalidOperationException();
    }

    public static implicit operator double(A a)
    {
        return a.value;
    }

    public static implicit operator A(double value)
    {
        return new A(value);
    }
}

public struct B
{
    private readonly double value;

    public B(double value)
    {
        this.value = value;
    }

    public static implicit operator double(B b)
    {
        return b.value;
    }

    public static implicit operator B(double value)
    {
        return new B(value);
    }
}

public class Example
{
    public void Method()
    {
        A a = 0.0d;
        B b = 0.0d;

        // QUESTION is there any way to show custom editor errors and/or make compilation fail?
        A result = a + b;
    }
}

As you can read in the example, I throw an exception if value types A and B are operands of an addition.

I'd like to show editor warnings and/or make the compilation fail. Is there any way to implement this behavior?

Upvotes: 0

Views: 111

Answers (2)

Igor
Igor

Reputation: 62318

is there any way to show custom editor errors and/or make compilation fail?

If you want this all you have to do is not define the + operator that you added in your code below "I want this operation to be prohibited".

See also dotnetfiddle.

Upvotes: 1

Felix K.
Felix K.

Reputation: 6281

That's the default behavior of the compiler if there is no conversion and you do not need to do anything.

But to do the conversion you need to overload operators ( sample from here ).

public static explicit operator Celsius(Fahrenheit fahr)
{
    return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}

There are also other operators which you can overload ( Sample from here ):

public static Fraction operator +(Fraction a, Fraction b)
{
    return new Fraction(a.num * b.den + b.num * a.den,
       a.den * b.den);
}

Upvotes: 4

Related Questions