I have 2 dictionaries. How I can assign DerivedClass dictionary to DerivedClass dictionary ?
Below code not worrking?
How can I change it?
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
class Program
{
static void Main(string[] args)
{
var derivedclass = new Dictionary<string, DerivedClass>();
var baseClass = new Dictionary<string, BaseClass>();
Dictionary<string, BaseClass> AAA = derivedclass;
Console.ReadKey();
}
}
You can't cast the dictionary directly, but you can create a new dictionary, something like this will work:
Dictionary<string, BaseClass> AAA =
derivedclass.ToDictionary(
k => k.Key,
v => (BaseClass)v.Value);
You can't. Dictionary
(along with all classes in C#) are invariant with respect their generic arguments.
And even if C# worked to support generic type variance on classes (rather than just interfaces and delegates) Dictionary
is conceptually not invariant with respect to the type of the value of the dictionary. You can add new values to a dictionary, so if you could cast a Dictionary<int, Tiger>
to a Dictionary<int, Animal>
then you could put a Chicken
in that dictionary of tigers, and we all know how well that would end.
If you had an IReadOnlyDictionary
interface it could potentially be covariant with respect to the type of the value, although the .NET implementation isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With