basically I\'m building a very generic T4 template and one of the things I need it to do is say print variable.ToString()
. However, I want it to evaluate lists and
Well, somewhat simple but... if you only have:
using System.Collections.Generic;
you might need to add:
using System.Collections;
The former defines IEnumerable<T>
and latter defines IEnumerable
.
This is an old question, but I wanted to show an alternative method for determining if a SomeType
is IEnumerable
:
var isEnumerable = (typeof(SomeType).Name == "IEnumerable`1");
If you want to test for the non-generic IEnumerable then you'll need to include a using System.Collections
directive at the top of your source file.
If you want to test for an IEnumerable<T> of some kind then you'll need something like this instead:
if (variable != null)
{
if (variable.GetType().GetInterfaces().Any(
i => i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
// foreach...
}
}