DomenPigeon
DomenPigeon

Reputation: 1127

How to cast ImmutableArray<DerivedClass> to ImmutablyArray<BaseClass> and vice versa in C#?

I know it's not possible to cast derived lists (why not is nicely explained here), but what about ImmutableArrays as they cannot be changed casting should be valid, right?

I would expect this to work:

class Animal {}
class Dog : Animal {}

ImmutableArray<Dog> dogs = ImmutableArray.Create<Dog>(new Dog());
ImmutableArray<Animal> animals = (ImmutableArray<Animal>) dogs;
ImmutableArray<Dog> dogsBack = (ImmutableArray<Dog>) animals;

Upvotes: 2

Views: 102

Answers (1)

DomenPigeon
DomenPigeon

Reputation: 1127

Yes this is possible:

ImmutableArray<Dog> dogs = ImmutableArray.Create<Dog>(new Dog());
ImmutableArray<Animal> animals = ImmutableArray<Animal>.CastUp(dogs);
ImmutableArray<Dog> dogsBack = animals.CastArray<Dog>();

Note that you could also use CastArray to cast from dogs to animals, but due to covariance, CastUp is a significantly faster than the CastArray method.

Upvotes: 3

Related Questions