Can't convert System.Object[] to System.Collections.Generic.List

3.2k views Asked by At

I have a method with an object parameter.

public bool ContainsValue(object value)

I found that converting the object to an IList works.

IList<object> list = (IList<object>)value;

However, converting it to a List does not.

List<object> Ilist = (List<object>)value;

I looked at the definition of both the IList and the List and they both seem to implement the Enumerator and Collection interfaces. I am wondering why List doesn't work but IList does. Where in the framework does it crash and why?

3

There are 3 answers

0
nogola On

If an object implements the IList interface, it doesn't mean that it is actually of the type List. It can be any other type implementing the IList interface.

0
Jan Zyka On

Not a C# expert, but might it be that IList is an interface while List is an implementation? It might be another implementation of IList ...

0
Matthew On

As others have said, you have two problems:

  1. An IList is not necessarily a List.
  2. The parameter for ContainsValue should probably be something more specific than object.

However, if for some reason the parameter must remain and object, and you require a List, rather than an IList, you can do this:

using System.Linq;

...

List<object> list = ((IList<object>)value).ToList();