Why does the result of IsGenericType differ in these examples?

I have functions, which generate collection of char objects:

public static IEnumerable<char> generic_foo<T>()
{
    return "1231";
}
public static IEnumerable<char> generic_foo2<T>()
{
    yield return '1';
    yield return '2';
    yield return '3';
}
public static IEnumerable<char> foo()
{
    return "1231";
}
public static IEnumerable<char> foo2()
{
    yield return '1';
    yield return '2';
    yield return '3';
}

public static void Main()
{
    var res = foo().GetType().IsGenericType;  //  False
    var gen_res = generic_foo<int>().GetType().IsGenericType;  //  False

    var res2 = foo2().GetType().IsGenericType;  //  False
    var gen_res2 = generic_foo2<int>().GetType().IsGenericType;  //  True
}

I was wondered by results of program. Why are result different? What is the key difference between foo2/generic_foo2 methods?

Jon Skeet
people
quotationmark

generic_foo2() is implemented by the compiler via a state machine. That state machine will be generic in T even though you're not actually using it - so calling GetType() on the instance of the state machine will give a generic type. It wouldn't be worth the compiler noting that you're never actually using T and creating a non-generic state machine... this is a rare corner case. (Why would you make a method generic and not use the type parameter anywhere?)

The state machine created for foo2() doesn't need to be generic because the method itself is not generic.

generic_foo() and foo are just returning strings though, and System.String is definitely not a generic type.

people

See more on this question at Stackoverflow