Cast to one of two types in C#

555 Views Asked by At

How can I cast to one of two types in C#?

Here is what I am trying to do:

public class BaseCl {}
public class Foo : BaseCl {}
public class Bar : BaseCl {}

BaseCl instance;
... some code which puts a value in the `instance`
var specificInstance = (instance as Foo) ?? (instance as Bar);

But I am getting an error:

Operator '??' cannot be applied to operands of type 'Foo' and 'Bar' [Assembly-CSharp] csharp(CS0019)

What am I missing here? I would expect the specificInstance to be of type Foo if the instance is also of type Foo or of type Bar if the instance is Bar. Because, if instance is not Foo I would expect the (instance as Foo) to be null.

1

There are 1 best solutions below

0
On BEST ANSWER

The whole point of type inference is that the type of a variable can be inferred from the initialising expression. How can the type of your variable be inferred when the initialising expression is supposed to be able to produce two different types? The type of a variable MUST be known at compile time because only then can you know what code you can write to use it. How could you possibly write code using that variable if it could be either type? What you're missing is that what you're trying to do is not possible.

If you want to handle both types then you will need to write conditional code, i.e. an if statement, to check for one type and then the other and declare a variable of each type to use in the two different cases.