-1

I know maybe this not a good way to create class but I just wondered why if else working but conditional

operator not and need implicit conversion

static void Main(string[] args)
    {
        dynamic myclass;

        if (true) /*some condition*/
        {
            myclass = new ClassA();
        }
        else
        {
            myclass = new ClassB();
        }

        myclass = true /*some condtion*/ ? new ClassA() : new ClassB();  //this line gives an error

      //Type of conditional expression cannot be determined because there is no implicit conversion between 'ConsoleApp4.ClassA' and 'ConsoleApp4.ClassB'

    }
sonertbnc
  • 1,580
  • 16
  • 26
  • Here's some more background on [union types](https://stackoverflow.com/q/3151702/4137916), which would do this in a safe manner. – Jeroen Mostert Jan 21 '20 at 11:10
  • 1
    Does this answer your question? [dynamic with ternary operator](https://stackoverflow.com/questions/20995623/dynamic-with-ternary-operator) – chrispepper1989 Jan 21 '20 at 11:12
  • so to expand on this something horrid like this dynamic myclass = true /*some condtion*/ ? (object)new ClassA() : (object)new ClassB(); would work because it forces ClassA and ClassB to be the same type. Equally if forced to any interface or base class it would work. But that would in turn force the dynamic type to that base / interface type – chrispepper1989 Jan 21 '20 at 11:18
  • I'm pretty sure that you were already ask similar question and I give the comment `var myclass = true ? new ClassA() : (object)new ClassB();` of course variable `myclass ` would have type objet then ... **C# is static typing ... change the language ...** – Selvin Jan 21 '20 at 11:25

1 Answers1

2

From documentation:

The type of consequent and alternative must be the same, or there must be an implicit conversion from one type to the other.

Miamy
  • 2,162
  • 3
  • 15
  • 32