3

I have a custom class named Optional< T >. This class overrides the implicit operator, something like this:

public static implicit operator Optional<T>(T value)
{
    return new Optional<T>(value);
}

public static implicit operator T(Optional<T> value)
{
    return value.value;
}

Ok, till now all fine, the direct operations like these work:

Optional<int> val = 33; //ok
int iVal = val; //ok

But, this doesn't work:

Optional<Optional<int>> val = 33; //error, cannot convert implicitly

So I'm wondering how can be supported the previous case.

Cheers.

1 Answer 1

3

You cannot chain user-defined implicit operators. If you define an implicit conversion from A to B, and from B to C, there is no implicit conversion from A to C that calls both. You'll either need to create a separate user-defined conversion from A to C, or have an explicit conversion to do half of the conversion for you.

Sign up to request clarification or add additional context in comments.

5 Comments

Can you add an example of how to use the explicit operator to help on this case? Thanks.
@Gusman If there is an implicit conversion from A to B and from B to C then you can write C c = (B)a;, since that only ends up using one implicit user-defined conversion.
Ok, I understand, I thought you meant to override the explicit operator. Thanks.
@Gusman Defining an implicit conversion operator implicitly allows explicit conversions to be performed using it. You don't need to (and in fact, can't) also define an explicit conversion for the same type conversion.
Yes, I know, because that I was puzzled :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.