Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top