Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?
Asked Answered
P

3

5

Please consider the following code:

class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{   
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict = 
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}

There is the error:

error CS1503: Argument '1': cannot convert from 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?

Panay answered 17/5, 2011 at 10:42 Comment(2)
You implement your own collections? If not, can't see any reason to avoid having static void foo(Dictionary<StudentType, List<Student>> students) that will solve this problem as well.Willettawillette
static void foo(IDictionary<StudentType, IList<Student>> students) is just for simplicity. Instead of foo() the IDictionary<> is passed to another part of my application, so it is necessary to use the IDictionary<> and IList<> to provide an abstraction.Panay
C
6

You could use the Linq ToDictionary method to create a new dictionary where the value has the correct type:

static void Main(string[] args)
{
  Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>();
  var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value);
  foo(dicTwo);
}
Calathus answered 17/5, 2011 at 10:49 Comment(0)
G
3

You will have build a new dictionary with the right types, copying the data from the old one into the new one.

Or, you could change the original dictionary to be of the right type to begin with.

Either way, no, you can't cast the dictionary.

The reason for this limitation is as follows:

  1. The dictionary contains values of type Student
  2. You could have many types that implement IStudent
  3. The method you're giving the cast'ed dictionary to could potentially try to stuff another IStudent into the dictionary, even if it isn't Student
Gabble answered 17/5, 2011 at 10:46 Comment(1)
I don't understand this answer. There is no IStudent in the question.Recourse
F
0

change the creation of studentDict to be:

Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>();
Fuddyduddy answered 17/5, 2011 at 10:47 Comment(4)
Sorry, but it is not an option. I need exactly this creation.Panay
Can you explain why you need exactly that creation? you can add a List<Student> to that creation. If you have already created the object elsewhere in your code then you will need to convert it by creating a new dictionary and casting the valuesFuddyduddy
Because I need to call List-specific member functions when I am getting it from the dictionary.Panay
the answer by @Calathus below will do what you requireFuddyduddy

© 2022 - 2024 — McMap. All rights reserved.