By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,853 Members | 1,012 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,853 IT Pros & Developers. It's quick & easy.

Nested Generic Dictionary Declaration

P: n/a
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.Gui d,System.Collections.Generic.IDictionary<System.Gu id,string>>'.
An explicit conversion exists (are you missing a
cast?) C:\Projects\DemoProject\Presenter\View\IncidentVie wState.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
Nov 25 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Nov 25 '07 #2

P: n/a
David Morris <dm******@newsgroup.nospamwrote:
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<objecto = 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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Nov 25 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.