Possible Duplicate:
Type result with conditional operator in C#
Basically I have some code like this:
IEnumerable<Effect> effects = ( ( activeOnly ) ? this.ActiveEffects : this.AllEffects ).Select ( e => e );
where:
this.ActiveEffects is:
class ActiveEffectList : IEnumerable<Effect>
this.AllEffects is:
class EffectList : IEnumerable<Effect>
which is why I expected the above statement to work, but it returns this compile error:
Type of conditional expression cannot
be determined because there is no
implicit conversion between
‘ImageEditor.ActiveEffectList’ and
‘ImageEditor.EffectList’
You can solve this problem by casting the first value to
IEnumerable<Effect>:The problem is that even though you’re assigning to IEnumerable, the compiler needs to evaluate the conditional expression before the cast happens and since the conditional statement needs both paths to return the same type, you are getting an error that
AllEffectscan’t be cast toActiveEffects.By casting the first value in the statement to IE
numerable<Effect>, you are forcing the conditional statement to returnIEnumerable<Effect>rather than one of the more specific types.