Re: Why is this invalid
- From: "Bruce Wood" <brucewood@xxxxxxxxxx>
- Date: 5 Apr 2007 11:01:46 -0700
On Apr 5, 10:40 am, "Larry Smith" <no_spam@xxxxxxxxxxx> wrote:
IDerived1 derived1 = GetDerived1();
IDerived2 derived2 = GetDerived2();
IBase ibase = (derived1 != null ? derived1 : derived2);
Where "IDerived1" and "IDerived2" each inherit from "IBase". The followinge
error results on the last line:
Error 32 Type of conditional expression cannot be determined because there
is no implicit conversion between 'Test.IDerived1' and 'Test.IDerived2'
I understand the error but why does the language consider it a problem in
this context. Thanks.
Because C# determines expression types independently of where that
expression is ultimately to be assigned.
In other words, the compiler sees this:
IDerived1 derived1 = GetDerived1();
IDerived2 derived2 = GetDerived2();
(derived1 != null ? derived1 : derived2);
and has no idea whether the result of the expression should be
IDerived1 or IDerived2 (or something else). It hasn't noticed (yet)
that you're going to assign the result to an IBase reference variable.
It just knows that the two parts of the expression have two different
types that have no available conversion.
Jon's solution is the correct one, although you don't need to cast
them both (assuming that IBase is the base interface for both
IDerived1 and IDerived2). If you cast just one, the compiler will
understand that it has to cast the other to the base type in order to
make the expression work:
derived1 != null ? (IBase)derived1 : derived2
.
- Follow-Ups:
- Re: Why is this invalid
- From: Jon Skeet [C# MVP]
- Re: Why is this invalid
- From: Larry Smith
- Re: Why is this invalid
- References:
- Why is this invalid
- From: Larry Smith
- Why is this invalid
- Prev by Date: Re: Why is this invalid
- Next by Date: Re: Why is this invalid
- Previous by thread: Re: Why is this invalid
- Next by thread: Re: Why is this invalid
- Index(es):
Relevant Pages
|
Loading