C# Converting object to List<object>

tobi picture tobi · Feb 15, 2017 · Viewed 7.4k times · Source

I need to convert a list of string to a list of object, but the thing is I am receiving this list as an object, because it's a parameter and I don't know what type it is.

This is the function that receives the parameter:

public static bool IsNotEmpty(object obj)
{
    if (obj is ICollection)
    {
        IList<object> collection = (IList<object>)obj; // The cast throws error here
        return IsNotEmpty(collection);
    }

    return true;
}

And this is the one this one uses:

public static bool IsNotEmpty<T>(IList<T> aList)
{
    return aList != null && aList.IsNotEmpty();
}

What can I do to cast it as a List of objects, so then I can pass it to the other function? (if there is a way)

Answer

Eric Lippert picture Eric Lippert · Feb 15, 2017

You are doing what we call an "XY question": you have a (wrong) solution in mind for your problem and you're asking about your wrong solution rather than seeking a solution to your actual problem.

You do not need to convert a list of string to a list of object in the first place, so there's no need to ask how to do that. The right solution to your problem is:

static class MyExtensions 
{
  public static bool Any(this IEnumerable sequence) 
  {
     if (sequence == null) 
       throw new ArgumentNullException ... etc ...
     if (sequence is ICollection)
       return ((ICollection)sequence).Any();
     foreach(object item in sequence)
       return true;
     return false;
   }
   public static bool Any(this ICollection collection)
   {
      if (collection == null) blah blah blah
      return collection.Count > 0;
   }
}

Great. Now your method is:

public static bool IsNotEmpty(object obj)
{
  if (obj is IEnumerable)
    return ((IEnumerable)obj).Any();
  else
    return true; 
}

The idea here is to first go to collection because that avoids enumerating the sequence unnecessarily. That can be expensive. But if we have a sequence that has items but is not a collection, then enumerate its first element. If we can do so successfully then it is not empty; if we cannot, then it is empty.

But more generally: the signature of your method is unfortunate. Don't get into the situation where you have an object in hand in the first place if you can possibly avoid it. How did you get into this situation?