Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Derived to Base dictionary

Tags:

c#

dictionary

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();
    }
}
like image 769
123498 Avatar asked Oct 12 '15 16:10

123498


2 Answers

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);
like image 59
DavidG Avatar answered Oct 04 '22 19:10

DavidG


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.

like image 39
Servy Avatar answered Oct 04 '22 20:10

Servy