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

I have an object that implements an interface IList

, I want to pass 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;

      

They do not work. Please help, thanks. To clarify:

b is an object passed as a parameter from the outside. It implements the 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
  }
}

      

+3


source share


3 answers


You cannot convert an existing object to IList<object>

unless it implements this interface, but you can easily create a new one List<object>

using LINQ:



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

      

+13


source


Found the answer:



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

      

+1


source


An IList

just isn't IList<object>

. It is highly unlikely that an object actually implements both interfaces, so the cast will simply fail. You will need to create a new list object that implements IList<object>

:

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

      

0


source







All Articles