Share via


Static method calls in generics

I go this question from a blog reader.

"The following code should be possible

     public class Class1
    {
        public static void Hi()
        {
            Console.WriteLine("Hi");
        }
    }

    public class Class2<T> where T : Class1
    {
        public static void Hi()
        {
            T.Hi();  //This should be possible. 
        }
    }

However, if you try to compile this then it fails with the "error: 'T' is a 'type parameter', which is not valid in the given context". At first to me it looked logical and symmetrical to be able to call static methods on a generic type by directly using the type parameter as during compile time it is known from the constrain that T is Class1 which has the static method Hi().

Then I sent this to the internal C# DL to get this clarified. Eric Lippert gave the answer.

     public class Class3 : Class1
    {
        public new static void Hi()
        {
            Console.WriteLine("By");
        }
    }

Since the user chose T.Hi() over Class1.Hi() it would mean that he expects a dynamic dispatch which lands in Class3.Hi(), but that is very misleading because by definition static methods are determined statically during compilation. So this option is pointless.

If the call always lands in Class1.Hi() as in the case of true static call it should be, then the user would be better off having it as Class1.Hi() which is what is supported.

Update: Just found that Eric has posted this on his blog. Check that out here

Comments

  • Anonymous
    June 18, 2007
    HmmmmThats great. and thanks to bring this thing to c# designers :)