I am writing a method that is passed an Object of any type.
If it is passed a string, it will process this string. If it is passed a class it will process any strings within this class. If this class also had classes, it will process any strings within those classes, and so on.
The code to do this is working really well. The only thing that isn't working is when a collection of class is passed to the method and I need to build some code to handle that.
I've created a non-working sample below that shows what I'm trying to do. In this sample I'm passing this into a generic. It works exactly the same if I swap out the T with an old fashioned Object.
private static void DoStuff<T>(T ObjectToUse)
{
if (ObjectToUse == null || !ObjectToUse.GetType().IsClass) return;
if (ObjectToUse.Count() > 0) //doesn't work
{
foreach (T i in ObjectToUser)
{
ProcessStuff(i);
}
}
else
{
ProcessStuff(ObjectToUse);
}
}
The problem I have is that T nor Object have a Count. If I use something like the below it returns false, which makes sense as ObjectToUse would be T, not a collection of itself.
if (ObjectToUse is ICollection<T>)
ObjectToUse.GetType() says the type is System.Collections.Generic.HashSet`1['classname']
I'd like to identify that its some form of array, and then cast this into something that I could loop through.
I checked the below, but receives an error saying that is ICollection requires one argument. Determine if object derives from collection type
Resolution:
private static void DoStuff(object ObjectToUse)
{
if (ObjectToUse == null || !ObjectToUse.GetType().IsClass) return;
if (ObjectToUse is IEnumerable<object>)
{
foreach (var obj in (IEnumerable<object>)ObjectToUse)
{
ProcessStuff(obj);
}
}
else
{
ProcessStuff(ObjectToUse);
}
}