Is there a benefit to overloading the explicit operator if implicit has been overloaded in C#?

310 views Asked by At

I am working with a structure that requires the implicit operator against strings and came across a basic question that I had not thought about.

public static implicit operator Version (string value) {...}

I can understand having only the explicit operator to enforce casting but cannot think of a situation where you would NEED it if the implicit operator is already overloaded. Is there one?

1

There are 1 answers

0
Servy On BEST ANSWER

There isn't. In fact, you cannot define both an implicit an explicit conversion operator for the same conversion. It is a compile time error:

public class Foo
{
    public static implicit operator Foo(string value)
    {
        Console.WriteLine("implicit");
        return null;
    }

    public static explicit operator Foo(string value)
    {
        Console.WriteLine("Explicit");
        return null;
    }
}

It gives the error of:

Duplicate user-defined conversion in type ...

If you define an implicit conversion you can write out an explicit conversion and it will use the implicit conversion's code to do the conversion, but there is no way of defining code for an implicit conversion and and explicit conversion that do different things.