joeb1415
joeb1415

Reputation: 547

Cast Dictionary<TKey, TValue> as Dictionary<TKey, TBaseValue>

Given:

class TKey {}
class TBaseValue {}
class TValue : TBaseValue {}

How can we cast

Dictionary<TKey, TValue>

As

Dictionary<TKey, TBaseValue>

And why can it not be done implicitly?

Upvotes: 0

Views: 50

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

Because Dictionary<TKey, TValue> is not read-only, you can't use covariance here (indeed, the type is declared without the out or in that would allow co-/contra-variance).

To illustrate why this is the case, just consider what would happen once you've cast to Dictionary<TKey, TBaseValue>. You're still dealing with the original dictionary, which has values that are supposed to only be TValue. But cast that way, you could add some different sub-class of TBaseValue (or even TBaseValue itself), which would violate the rules of the original object's type.

Basically, this is C#'s way of preventing you from making a big mistake. :)

Upvotes: 1

Related Questions