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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With