C# Compiler Awkwardness

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

In the following code, I get a compile error referring to the "return"
statement.

static object GetMultiColorElement(string s, bool isFade)
{
//...

return isFade ?
new ChatMessageFadeTagElement(colors) :
new ChatMessageAltTagElement(colors);
}

The compile error message is:

[begin]
Type of conditional expression can't be determined because there is no
implicit conversion between 'ChatMessageFadeTagElement' and
'ChatMessageAltTagElement'
[end]

'ChatMessageFadeTagElement' and 'ChatMessageAltTagElement' are both
direct subclasses of 'object'.

The following resolves the error:

static object GetMultiColorElement(string s, bool isFade)
{
//...

return isFade ?
new ChatMessageFadeTagElement(colors) :
new ChatMessageAltTagElement(colors)
as object;
}

Why do I need to cast here?
 
C# Learner said:
In the following code, I get a compile error referring to the "return"
statement.

Why do I need to cast here?

From the C# spec:

<quote>
The second and third operands of the ?: operator control the type of
the conditional expression. Let X and Y be the types of the second and
third operands. Then,

* If X and Y are the same type, then this is the type of the
conditional expression.
* Otherwise, if an implicit conversion (§13.1) exists from X to Y,
but not from Y to X, then Y is the type of the conditional expression.
* Otherwise, if an implicit conversion (§13.1) exists from Y to X,
but not from X to Y, then X is the type of the conditional expression.
* Otherwise, no expression type can be determined, and a compile-
time error occurs.
</quote>

Basically you've got to let the compiler know that the type of the
whole expression really should be "object" in your case.
 
Back
Top