Cast received object to a List<object> or IEnumerable<object>

C#.Net

C# Problem Overview


I'm trying to perform the following cast

private void MyMethod(object myObject)  
{  
    if(myObject is IEnumerable)  
    {
        List<object> collection = (List<object>)myObject;  
        ... do something   
    }  
    else  
    {  
        ... do something  
    }  
}

But I always end up with the following excepction:

Unable to cast object of type 'System.Collections.Generic.List1[MySpecificType]' to type 'System.Collections.Generic.List1[System.Object]'

I really need this to work because this method needs to be very generic to receive single objects and collections both of unspecified types.

Is this possible, or is there another way of accomplishing this.

Thank you.

C# Solutions


Solution 1 - C#

C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like

IList collection = (IList)myObject;

Solution 2 - C#

You can't cast an IEnumerable<T> to a List<T>.

But you can accomplish this using LINQ:

var result = ((IEnumerable)myObject).Cast<object>().ToList();

Solution 3 - C#

Problem is, you're trying to upcast to a richer object. You simply need to add the items to a new list:

if (myObject is IEnumerable)
{
   List<object> list = new List<object>();
   var enumerator = ((IEnumerable) myObject).GetEnumerator();
   while (enumerator.MoveNext())
   {
      list.Add(enumerator.Current);
   }
}

Solution 4 - C#

Do you actually need more information than plain IEnumerable gives you? Just cast it to that and use foreach with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable (or IList to access it like a list) works very well.

Solution 5 - C#

This Code worked for me

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

Solution 6 - C#

How about

List<object> collection = new List<object>((IEnumerable)myObject);

Solution 7 - C#

Have to join the fun...

	private void TestBench()
	{
		// An object to test
		string[] stringEnumerable = new string[] { "Easy", "as", "Pi" };

		ObjectListFromUnknown(stringEnumerable);
	}

	private void ObjectListFromUnknown(object o)
	{
		if (typeof(IEnumerable<object>).IsAssignableFrom(o.GetType()))
		{
			List<object> listO = ((IEnumerable<object>)o).ToList();
			// Test it
			foreach (var v in listO)
			{
				Console.WriteLine(v);
			}
		}
	}

Solution 8 - C#

Nowadays it's like:

var collection = new List<object>(objectVar);

Solution 9 - C#

You need to type cast using as operator like this.

private void MyMethod(object myObject)  
{  
if(myObject is IEnumerable)  
{
    List<object> collection = myObject as(List<object>); 
    ... do something   
}  
else  
{  
    ... do something  
}  
}      

Solution 10 - C#

You could also convert object to a list of your DTO.

First serialize myObject and then deserilize it into your List.

Here is the code:

List<MyDto> myList = JsonConvert.DeserializeObject<List<MyDto>>(JsonConvert.SerializeObject(myObject));

The Newtonsoft.Json is used in the above code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergio RomeroView Question on Stackoverflow
Solution 1 - C#erikkallenView Answer on Stackoverflow
Solution 2 - C#andleerView Answer on Stackoverflow
Solution 3 - C#Chris HolmesView Answer on Stackoverflow
Solution 4 - C#Jon SkeetView Answer on Stackoverflow
Solution 5 - C#Manish NayakView Answer on Stackoverflow
Solution 6 - C#Cameron MacFarlandView Answer on Stackoverflow
Solution 7 - C#IVSoftwareView Answer on Stackoverflow
Solution 8 - C#Tropin AlexeyView Answer on Stackoverflow
Solution 9 - C#user5093161View Answer on Stackoverflow
Solution 10 - C#Mustafa BazghandiView Answer on Stackoverflow