Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# allow types that use composition to have implicit conversions for interfaces? [duplicate]

Possible Duplicate:
Why can't I use interface with explicit operator?

When I do this:

public struct Effect
{
    public IEffect IEffect { get; private set; }

    public Effect ( IEffect effect )
    {
        this.IEffect = effect;
    }

    public static implicit operator IEffect ( Effect effect )
    {
        return effect.IEffect;
    }

    public static explicit operator Effect ( IEffect effect )
    {
        return new Effect ( effect );
    }
}

I get a compiler error like this:

'ImageEditor.Effect.implicit operator ImageEditor.IEffect(ImageEditor.Effect)': user-defined conversions to or from an interface are not allowed.

Why are they not allowed? Is this not a good practice?

like image 314
Joan Venge Avatar asked Jan 31 '11 18:01

Joan Venge


1 Answers

This is detailed in section 10.10.3 of the C# language spec.

The summary reason of why though is ...

  • Conversion operators should not replace built-in conversions. Allowing this just leads to extremely confusing behavior
  • In general it's not possible to determine if an implicit conversion to an interface is replacing a built-in conversion and hence it's disallowed
like image 169
JaredPar Avatar answered Oct 28 '22 00:10

JaredPar