2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<object> list = new List<object>();
            List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();

            Dictionary<string, object> master = new Dictionary<string, object>();
            master.Add("list", list);
            master.Add("dict", dict);

            List<object> mydict = (List<object>)master["dict"]; // this is where i get exception
            Console.Write("Count: ", mydict.Count);
        }
    }
}

It is throwing exception on bold line. Why is this behaviour and how shall i access this element? Thanks Sumanth

Ehsan
  • 31,833
  • 6
  • 56
  • 65
sumanthmp
  • 21
  • 4
  • You can only cast it to `List>`. `List>` cannot be casted to `List` in most cases. Please read http://msdn.microsoft.com/en-us/library/dd799517.aspx to learn more about convariance and contravariance. – Lex Li Aug 13 '13 at 09:16

4 Answers4

5

Because there is no List<object> under dict key

var mydict = (List<Dictionary<string, object>>)master["dict"];
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
3

The value master["dict"] is a List<Dictionary<string, object>>, while the code casts it to a List<object>. That does not work because List<T> is invariant on the type T. To use a simpler example, this is not valid:

var list = new List<string>();
var listOfObjects = (List<object>)list;

If you somehow know the type of item you are pulling out of master then you can cast it back to its proper type:

var masterDict = (List<Dictionary<string, object>>)master["dict"];

Alternatively, you could cast the value to IEnumerable<object> because that interface is covariant on its type parameter:

// This is not really meaningful because you can cast to non-generic IEnumerable
// just as well, but it works as a demonstration of what is possible.
var mycollection = (IEnumerable<object>)master["dict"];
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
0

you are trying to get a List<Dictionary<string, object>> as a List<object> and probably thinking Dictionary<string, object> is an object right?

yes, that's right, but List<Dictionary<string, object>> does not inherit List<object> and therefor the conversion you are using is invalid!

as people before me said: do

(List<Dictionary<string, object>>)master["dict"];
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0

If you need IEnumerable or ICollection methods you can cast to non generic interface like:

        ICollection mydict = (ICollection)master["dict"];
        Console.Write("Count: ", mydict.Count);
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116