Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?

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?

like image 213
Sergey Vyacheslavovich Brunov Avatar asked May 17 '11 10:05

Sergey Vyacheslavovich Brunov


2 Answers

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);
}
like image 65
ColinE Avatar answered Oct 23 '22 10:10

ColinE


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
like image 3
Lasse V. Karlsen Avatar answered Oct 23 '22 10:10

Lasse V. Karlsen