1

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Benjamin
  • 291
  • 3
  • 12
  • First problem: Why is your parameter declared as type `object` in the first place? You're obviously using a version of the Framework that supports generics: **use them**. Second problem: you forgot to tell us what type your `object` instance is. – Cody Gray - on strike Mar 02 '11 at 05:44

3 Answers3

1

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

Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
0

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.

nogola
  • 214
  • 4
  • 12
0

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();
Matthew
  • 28,056
  • 26
  • 104
  • 170