-1

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.

qqqqqqq
  • 1,831
  • 1
  • 18
  • 48
  • the thing is: even though every `Foo` and every `Bar` is a `BaseCl`, _no_ `Foo` ever is a `Bar` and vica versa. so what should your `specificInstance` be able to hold? `Foo` or `Bar`? because _both_ is not possible. you have to handle both cases separately. or, to answer your opening question directly: you can't. – Franz Gleichmann May 22 '21 at 08:48
  • `if (instance is Foo foo) { /* Use \`foo\` */ } else if (instance is Bar bar) { /* Use \`bar\` */ }` – 41686d6564 stands w. Palestine May 22 '21 at 09:06
  • Imagine that you *could* do this, and that Foo had a method called `FooMethod()` and Bar had a method called `BarMethod()`. What would you expect `specificInstance.FooMethod()` to do if `specificInstance` was actually a `Bar`? – Matthew Watson May 22 '21 at 09:07

1 Answers1

3

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.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46