2

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; 
2
  • 1
    Why would you want to? Can't you access dogs as if it contained Animal instances or add Dog instances to animals on creation? Commented Aug 16, 2023 at 8:24
  • @ChrisBD I need this for a caching scenario, I made an example here Commented Aug 16, 2023 at 8:53

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you need ImmutableArray's CastUp? dogs.CastArray<Animal>() should be enough?
@PeterCsala both operations simply cast the underlying array with zero copy; "enough" suggests a difference - if anything, CastUp is preferable since it exploits a known covariance operation, rather than an unknown blind cast with type-test; source, for the curious: github.com/tunnelvisionlabs/dotnet-collections/blob/master/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.