Alex Rivera | Logout

How to convert Object to List<MyClass>?

Asked 2011-03-09T20:44:24.380
12

I am trying to make a generic method that can accept any object, in which, even the object is List<AnyClass>. Something like:

public static void MyMethod(object _anyObject)
{

}

So in my method it accept the parameter as Object, then I will determine what to do by their type to do

So when I know that's a List type, I want to convert that Object back to List<AnyClass>, iternate each object and their propertie

I tried to do:

List<object> ObjectList = object as List<object>;

But it will return null, because the object originally is List<AnyClass>

Thanks in advance

================

Edit: Sorry, seems like I haven't make it clear, because I simplifed the problem... I means the Object might be:

_anyObject = List<Class1>
_anyObject = Class2
_anyObject = DataSet
_anyObject = AnyClass
_anyObject = List<object>

So say, the user can even put in a List<object>, but each of the object in that list can be different class..That's why I can't use <T>.

The original of my problem is:

public static void MyMethod(List<object> _anyList)
{

}

Then I don't care what they put into the list, even the object in the list contains another object list...

c#
Edit
Report

1 Answer

3

List<object> is a different type than e.g. List<int>. That's why your cast fails.

Depending on what your goal is, you should choose a different solution. It seems your method needs to be able to handle lists and normal objects.

List<T> does implement IEnumerable, which allows you to enumerate all elements.

public static void MyMethod( object _anyObject )
{
    IEnumerable list = _anyObject as IEnumerable;
    if ( list != null )
    {
        foreach ( var item in list )
        {
            // Do whathever you want.
        }
    }
    else
    {
        // Probably just a plain object, not a collection.
    }
}
answered 2011-03-09T20:54:46.090

Your Answer