Lance H
Lance H

Reputation: 954

C# How to convert an object with IList to IList<object>?

I have an object which implements IList interface, I want to cast it to IList<object> or List<object>, I tried

IList<object> a=(IList<object>)b;
List<object> a=(IList<object>)b;
IList<object> a=(List<object>)b;
List<object> a=(List<object>)b;

These are not working. Please help, thanks. To clarify:

b is an object pass as parameter from outside. It implements IList interface. For example,

public class a
{
  string name;
  List<a> names;
}
public void func(object item)
{
  object dataLeaves = data.GetType().GetProperty("names").GetValue(dataInput, null);
  if (dataLeaves != null && dataLeaves.GetType().GetInterfaces().Any(t =>t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IList<>)))
  {
    List<object> a=(List<object>) dataLeaves; //Need to convert the dataLeaves to list or IList
  }
}

Upvotes: 4

Views: 17931

Answers (3)

Lance H
Lance H

Reputation: 954

Found the answer:

IEnumerable<object> a = dataLeaves as IEnumerable<object>;

Upvotes: 3

Servy
Servy

Reputation: 203811

An IList simply isn't an IList<object>. It's highly unlikely that the object actually implements both interfaces, so the cast just won't ever succeed. You'll need to create a new list object that does implement IList<object>:

IList<object> a= b.OfType<object>.ToList();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500485

You can't convert the existing object to an IList<object> if it doesn't implement that interface, but you can build a new List<object> easily using LINQ:

List<object> = b.Cast<object>().ToList();

Upvotes: 17

Related Questions