Nested Generic Dictionary Declaration

D

David Morris

I am trying to create a nested Dictionary and get an error that seems odd to
me. Here is my declaration:

private IDictionary<Guid, IDictionary<Guid, string>>
myNestedDictionary
= new Dictionary<Guid, Dictionary<Guid, string>>();

I get an error unless I nest a Dictionary and not an IDictionary:

Error 3 Cannot implicitly convert type
'System.Collections.Generic.Dictionary<System.Guid,System.Collections.Generic.Dictionary<System.Guid,string>>'
to
'System.Collections.Generic.IDictionary<System.Guid,System.Collections.Generic.IDictionary<System.Guid,string>>'.
An explicit conversion exists (are you missing a
cast?) C:\Projects\DemoProject\Presenter\View\IncidentViewState.cs 29 15 Presenter

So this works:
private IDictionary<Guid, Dictionary<Guid, string>>
myNestedDictionary
= new Dictionary<Guid, Dictionary<Guid, string>>();

I would rather deal with the interface but I am forced to the implentation.

Thanks,

David Morris
 
M

Marc Gravell

What you mean is:

private IDictionary<Guid, IDictionary<Guid, string>>
myNestedDictionary
= new Dictionary<Guid, IDictionary<Guid, string>>();

i.e. a concrete implementation of a dictionary between guid and an
abstract dictionary - then you might use:


myNestedDictionary.Add(someGuid, new Dictionary<Guid, string>());

As a side note; since this is private there isn't much harm using the
concrete name anyway...

Marc
 
J

Jon Skeet [C# MVP]

David Morris said:
I am trying to create a nested Dictionary and get an error that seems odd to
me.

You're basically running against the lack of variance in generics in
C#. It's exactly the same as trying:

List<object> o = new List<string>();

Consider what happens with the above if you write:

o.Add(new object());

Or indeed in your case, if you tried

myNestedDictionary[Guid.Empty] = new SomeOtherIDictionaryImpl();


There's considerable discussion about whether it should be supported
where safe for future versions though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top