Search code examples
c#genericstypesinstanceinner-classes

Why does this code replace float with long?


I have this code as an example:

class A<T> {
    public class B : A<long> {
        public void f() {
            Console.WriteLine( typeof(T).ToString());
        }
 
    public class C : A<long>.B { }
    
    } 
}

class Prg5 { static void Main() {
    var c = new A<float>.B.C();
    c.f();
} }

With output:

System.Int64

Why does it print the type for long? How and where does the float type passed originally get replaced?


Solution

  • The type C is defined as:

    public class C : A<long>.B { }
    

    The type A is defined as:

    class A<T> {
        public class B : A<long> {
            public void f() {
                Console.WriteLine( typeof(T).ToString());
            }    
    
        public class C : A<long>.B { }
        } 
    }
    

    So if you create a new C then the type parameter for A is long.

    In the statement var c = new A<float>.B.C();, A<float> and B are just parts of the "path" to the nested class C. The fact that A<float> is part of that path does not change the fact that C is an A<long>.B.

    The float parameter and the fact that B is an A<long> are not relevant to determine the type of T inside c.f().