Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I write an implicit operator from a Base class to a Derived class in C#?

Tags:

operators

c#

public class Derived : BaseClass
{
    public Derived(string name) : base(name) {}

    public static implicit operator BaseClass(Derived derived)
    {
        return new BaseClass(derived.ColorHex);
    }

    public static implicit operator Derived(BaseClass baseclass)
    {
        return new Derived(baseclass.name);
    }
}

This won't work. why isn't it allowed?
I can potentially write the logic necessary for it to make sense, especially when converting from the base to the derived one.

EDIT:Changed the title of the question

like image 243
Stéphane Avatar asked Jun 01 '12 15:06

Stéphane


1 Answers

Because there is already an implicit conversion from Derived to BaseClass, and the converse does not make any sense.

Regarding the latter: if your Base objects are meant to be implicitly convertible to Derived -- why aren't they Derived objects in the first place?

Obligatory quotes from the standard:

6.1.6 Implicit reference conversions

The implicit reference conversions are:

  • [...]
  • From any class-type S to any class-type T, provided S is derived from T.

This says there's an implicit conversion Derived => Base, as we all know.

6.2.4 Explicit reference conversions

The explicit reference conversions are:

  • [...]
  • From any class-type S to any class-type T, provided S is a base class of T.
  • [...]

This says there's already an explicit conversion Base => Derived (which is what allows you to try downcasting at runtime).

6.4.1 Permitted user-defined conversions

C# permits only certain user-defined conversions to be declared. In particular, it is not possible to redefine an already existing implicit or explicit conversion.

And this says that since the two conversions of interest are already defined by the language, you can't redefine them.

like image 89
Jon Avatar answered Nov 14 '22 22:11

Jon