0

Why am I not allowed to do this:

private Base Property => m_IsAbsolute ? new A() : new B();

Compiler complains about 'No implicit conversion between A and B

I can fix that by casting B to Base, but why on earth would I need to do that?

While I am allowed to do this:

private Base Property2
{
    get
    {
        if (m_IsAbsolute)
        {
            return new A();
        }
        return new B();
    }
}

For reference the classes used in above example:

class Base
{
}

class A : Base
{
}

class B : Base
{        
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
bas
  • 13,550
  • 20
  • 69
  • 146
  • 1
    That is allowed in C# 9 AFAIK; it wasn't before, because on the moment parser sees `condition ? new A()` it implicitly types the expression as `A` even if hierarchy contains common superclass for both branches. And yes, it looks like mistake in design – Андрей Саяпин Nov 09 '20 at 09:03
  • 1
    @АндрейСаяпин - no, it doesn't assume `A`. It considers both sides of the `:` equally but it does want to pick *one* of the two actual types. – Damien_The_Unbeliever Nov 09 '20 at 09:04
  • 1
    That's not quite true. C# 9 still refuses to go looking for a common base type between `A` and `B`, but it will target-type the expression: so `var x = true ? new A() : new B()` doesn't work in C# 9, but `Base x = true ? new A() : new B()` does. [See here](https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQBMQGoA+ABATARgFgAoE7AZgAI9KBhSgbxMpequwBZKBZACgEpGzViIBuEBJQAelALyUYCAK5xKAfkoA7OAHdKAQQGUQW3ZQBCAgNzCWAXxIPiIsrgvQ4JJsSeuDx9yhPYm9fYhpzAPMPLxEXHyA===) – canton7 Nov 09 '20 at 09:11

0 Answers0