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
.