How to determine if object is of type IEnumerable
Code:
namespace NS {
class Program {
static IEnumerable GetInts()
You can use the is
keyword.
[TestFixture]
class Program
{
static IEnumerable<int> GetInts()
{
yield return 1;
}
[Test]
static void Maasd()
{
var i = GetInts();
Assert.IsTrue(i is IEnumerable<int>);
}
}
Same technique as Marc's answer, but Linqier:
namespace NS
{
class Program
{
static IEnumerable<int> GetInts()
{
yield return 1;
}
static void Main()
{
var i = GetInts();
var type = i.GetType();
var isEnumerableOfT = type.GetInterfaces()
.Any(ti => ti.IsGenericType
&& ti.GetGenericTypeDefinition() == typeof(IEnumerable<>));
Console.WriteLine(isEnumerableOfT);
}
}
}
Try
type.GetInterface("IEnumerable") != null && type.IsGenericType