I have generated an extension method to display a IList<T>
in a meaningful manner:
public static class IListExtension
{
public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
{
string display = string.Empty;
// create the display string from the elements of this list
return display;
}
}
To use this extension I can do this:
IList<someClass> myList = CreateList();
myList.ToDisplay();
My problem is now, that I have a method that gets an object
, which also can be a list. So, if the object is no list, I want to use the ToString()
method, if it IS a list, I want to use my extension.
public string CreateDisplayString(object element)
{
if (element == null)
return string.Empty;
if (element as IList<T> != null)
return (element as IList<T>).ToDisplay();
return element.ToString();
}
Obviously, the code above does not work, because I cannot cast to the generic IList<T>
. If I use an existing class, like IList<string>
it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>
. Is there a way to use the extension method or any other means to get a custom string from a list of any type?