So I'm creating a generic method, obviously the signature therefore can take any type of object. The problem I have is I want the user to be able to either just send one object to my method, or a collection (I know, different interface from IEnumerable) of objects. Now because (T obj) could be one object, or it could be a list or an array of objects, Im not sure how to check and alter behaviour depending on if it is a collection or not.
This is what I have, and I'm getting a compiler error CS1061, T does not contain a definition for FirstOrDefault. Which makes sense, because it might not. But as far as I can tell my conditional should have checked if it does or not.
if (typeof(IEnumerable<T>).IsAssignableFrom(obj.GetType()))
{
foreach (var info in obj.FirstOrDefault().GetType().GetProperties())
{
members.Add(info.Name, info.GetValue(obj).ToString());
}
}
else
{
foreach (var info in obj.GetType().GetProperties())
{
members.Add(info.Name, info.GetValue(obj).ToString());
}
}
In case it makes any difference, members is a Dictionary<string, string>. At this stage I'm only trying to get it to accept both collections and single objects, I can work out the behaviour later.