C# create class with conditional operator

506 views Asked by At

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'

    }
1

There are 1 answers

0
Miamy On

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.