Gusman
Gusman

Reputation: 15161

Nested implicit operator

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.

Upvotes: 3

Views: 401

Answers (1)

Servy
Servy

Reputation: 203812

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.

Upvotes: 3

Related Questions