Benjamin
Benjamin

Reputation: 291

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

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?

Upvotes: 1

Views: 3439

Answers (3)

Matthew
Matthew

Reputation: 29206

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

Upvotes: 0

Jan Zyka
Jan Zyka

Reputation: 17898

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 ...

Upvotes: 1

nogola
nogola

Reputation: 214

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.

Upvotes: 0

Related Questions