The quirky ?:


If there was ever a poll conducted for the most favorite C# operator, I’d guess the conditional operator ?:, also known as the ternary operator, will win hands down. I find it to be one of those tools that make things shorter and clearer at the same time. But how well do you know the operator?



What do you think is wrong with the following piece of code?



    interface IDoer {}

    class ADoer : IDoer { }
    class BDoer : IDoer { }
    class Program
    {
        static void Main(string[] args)
        {
            bool flag = bool.Parse(args[0]);
            IDoer doer = flag ? new ADoer() : new BDoer();
        }
    }

Looks straightforward, doesn’t it? Yet, this does not compile; the error being



error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'ADoer' and 'BDoer'

The C# spec says that the two expressions that appear on either side of the : must be one of the following

  • Both of them should be of the same type
  • The first one should be convertible to the second
  • The second one should be convertible to the first


In the above case, ADoer and BDoer are both convertible to IDoer (because they implement IDoer), but because neither of them is implicitly convertible to the other, compilation fails. It doesn’t matter to the compiler that the result of the expression is always convertible to IDoer, all it cares about is the deduction of the type of the ternary expression.



I guess this is one of those places where static typing gets in the way of the developer, instead of helping him. You win some, you lose some :)



One thought on “The quirky ?:”

  1. Great one. Have not come across that usage but have come on similar ones.

    I ma not sure if this one relates to the ternatory operator:-

    I have List and a method that takes List, i cannot pass that List, same with a method that takes List.

    Regards
    Vivek Ragunathan

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>