SortedDictionary<string, XYZ> to SortedDictionary<string, object>

Hello,

I have in C#, ASP.NET 3.5 the following code

public class ABC{
public class XYZ {
  some implementation
}
}

Then I have a method that takes an arg of type SortedDictionary<string, object>. When I try to pass in SortedDictionary<string, ABC.XYZ>, I get the following compile error:
'System.Collections.Generic.SortedDictionary<string,ABC.XYZ>' to 'System.Collections.Generic.SortedDictionary<string,object>'      

Why? ABC.XYZ is of type object, isn't it? Any idea how to go around this in a clever way?
bovlkAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
_Katka_Connect With a Mentor Commented:
Hi, I would try to make the method generic as in

public void MyMethod<TCollectionType>(TCollectionType collection) { }

And then call it with MyMethod<SortedDictionary<x, y>>(dictionary).

regards,
Kate
0
 
_Katka_Commented:
Or a bit more clever you can do it by

public void MyMethod<TKey, TValue>(SortedDictionary<TKey, TValue> collection) { }

regards,
Kate
0
 
bovlkAuthor Commented:
Still a question: why does not the SortedDictionary work?
0
 
bovlkAuthor Commented:
BTW, it was even simpler
public void MyMethod<T>(string s, int i, SortedDictionary<string, T> values)
{
}
works amazingly well.
0
 
_Katka_Commented:
You're welcome. :)

To explain to you. Generics have to of exactly the same type.

http://stackoverflow.com/questions/1431636/htmlhelperchildtype-not-assignable-to-htmlhelpermothertype

By moving them to single parameters the check is not:

SortedDictionary<x, y> vs SortedDictionary<x, z>

but rather

x vs x => ok
y vs z => when z is derived from y => ok

regards,
Kate
0
All Courses

From novice to tech pro — start learning today.