vendredi 4 mars 2016

Why won't the shorthand version of my 'if' compile with different implementations? [duplicate]

This question already has an answer here:

I have the following interface:

interface IMyInterface {}

And the following two implementations:

class MyImplementation : IMyInterface {}

class MyOtherImplementation : IMyInterface {}

Given that, the following compiles:

IMyInterface ReturnImplementation()
{
   if(condition)
   {
      return new MyImplementation();
   }
   else
   {
      return new MyOtherImplementation();
   }
}

But this does not:

IMyInterface ReturnImplementation()
{
   return condition ? new MyImplementation() : new MyOtherImplementation();
}

Question

Why? What am I misunderstanding in assuming that it should compile? Is it as simple as the fact that the shorthand if specifies the exact same type is chosen from? If so, why? Why is it restricted in this way?

Aucun commentaire:

Enregistrer un commentaire