Re: Why is this invalid



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

.



Relevant Pages

  • Re: Why is this invalid
    ... In other words, the compiler sees this: ... 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). ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: new vs override - a practical example
    ... interpret it as without using the cast operator -- which is the issue here. ... * From any class-type S to any class-type T, provided S is derived from T. ... * From any class-type S to any interface-type T, ... Implicit conversion is exactly implicit. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: C/C++ guidelines
    ... So it's _not_ the usage of the cast which "might introduce ... subtle errors" but forgetting to include. ... Its a warning and no diagnosis is actually required. ... If you rely on getting a useful diagnostic for an implicit conversion ...
    (comp.lang.c)
  • Re: Terminology : casting/conversion
    ... It is certainly more consistent ... to use the phrase "implicit conversion". ... standard defines "cast" as, in effect, "the syntactic construct ... Note that the same sequence of six "int" constants might be used ...
    (comp.lang.c)
  • Re: Terminology : casting/conversion
    ... It is certainly more consistent ... to use the phrase "implicit conversion". ... standard defines "cast" as, in effect, "the syntactic construct ...
    (comp.lang.c)

Loading