Mr.Gomer
Mr.Gomer

Reputation: 649

Converting a object into a List<object> C#

I have a method as such:

 if (value != null && value.GetType().IsGenericType &&
                value.GetType().GetGenericTypeDefinition() == typeof(List<>))
            {
                SetDropDownList(value)
            }

The if statement is applied to a list that can contain lists. Now when it finds a list I send it to the method SetDropDownList(). This method signature looks like this:

public void SetDropDownList(object list)
        {
            
        }

Now my question is, is it possible to check what the list contains and cast it as that type. So say its a list of strings (List). can I do something like

{
var listType = list.GetType();
List<listType> mylist = new List<listType>();
}

Now i know this code would never work but i just want you to get some idea of what i am trying to do. Thx

Upvotes: 0

Views: 85

Answers (2)

Chris Schaller
Chris Schaller

Reputation: 16554

If the passed in list IS a type, we can use type pattern matching to simplify this sort of logic, especially if there are multiple known or expected types:

public void SetDropDownList(object list)
{
    if (list is List<listType> typedList)
    {
        // TODO: do something with this typed list
        Console.WriteLine(typedList.Count());
    }
    else if (list is IEnumerable genericList)
    {
        // this is a catchall for enumerable sources, again using pattern matching to simplify the syntax
        foreach(var item in genericList)
        {
            // deal with the item
            Console.WriteLine(item.ToString());
        }
    }
    else
        throw new NotImplementedException("list type not recognised: " + list.GetType().Name);
}

Upvotes: 1

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You could check if the object is an IEnumerable.

For example:

object obj = new List<string>();

if(obj is IEnumerable list)
    foreach(var item in list)
        Console.WriteLine(item.ToString());

Upvotes: 1

Related Questions