0

I need help, the next code works:

class A{}
class B:A{}
class C:A{}

A a;
if (Console.ReadLine() == "A")
    a = new B();
else
    a = new C();

Then why this doesn't:

A a = (Console.ReadLine() == "A") ? new B() : new C();
wic
  • 362
  • 3
  • 14
  • 4
    Because they return different types.With a cast it would work: `A a = (Console.ReadLine() == "A") ? (A)new B() : (A)new C();` – Alexander Derck Jan 13 '19 at 22:52
  • 3
    Just one of the `(A)` would be sufficient I suspect @AlexanderDerck. – mjwills Jan 13 '19 at 22:52
  • From [the documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator): *"The type of consequence and alternative must be the same, or there must be an **implicit conversion** from one type to the other."* – Rufus L Jan 13 '19 at 22:59

0 Answers0