sumanthmp
sumanthmp

Reputation: 21

exception on accessing dictionary from list

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

Upvotes: 2

Views: 130

Answers (4)

Piotr Stapp
Piotr Stapp

Reputation: 19830

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);

Upvotes: 0

Jon
Jon

Reputation: 437376

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"];

Upvotes: 3

No Idea For Name
No Idea For Name

Reputation: 11577

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"];

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

Because there is no List<object> under dict key

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

Upvotes: 5

Related Questions