Reputation: 1697
I want to pass in an unknown object to a method, and then let it return the object as a List. Basically, I want something like this
object b = new MyType();
object a = new List<MyType>()
public List<object> convertObjectBackToList(object Input)
{
//if Input is an IList type (Ex: object a above)
//return List<object>;
//if Input is an generic object type. (Ex: object b above)
//return an List<object> which has only one object.
List<object> Output = new List<object>();
Output.Add(Input);
return Output;
}
Upvotes: 0
Views: 3834
Reputation: 15364
You can cast your object first to IEnumerable
, then convert to list.
public List<object> convertObjectBackToList(object Input)
{
if(Input is IEnumerable)
return ((IEnumerable)Input).Cast<Object>().ToList();
return new List<Object>() { Input };
}
EDIT
A generic extension method would even be better
public static partial class SOExtensions
{
public static List<T> ToList2<T>(this object Input)
{
if (Input is IEnumerable)
return ((IEnumerable)Input).Cast<T>().ToList();
return new List<T>() { (T)Input };
}
}
Then you could use it as
var list1 = someObject.ToList2<SomeType>();
Upvotes: 6