Calling static method on a generic class

c#, generics

Solution

When you do `Program1 : Program`, you are telling all Program1 instances are not only of type Program1, but also of type Program, because it inherits it.

But when you do `Program1<T>`, you are telling Program1 can have any independent type parameter in addition of it's own type, to do things with that independent type.

In case you use `Program1 : Program`, your static method can do the following:

class Program1 : Program
{
    public static void check()
    {
        Program.Main() // but the real good thing to do is just avoid this check method.
        // and use just Program1.Main() in other places
    }
}

In the case of using `Program1<T>`, I can't see anything that explains that usage, unless you are trying to do some further thing we didn't read in the question. Here, T is not really program, even if you set the constraint as you did. T is a mere generic type. The reasons to use it is to allow your class to work with different types. If you are working with only one type, there's no reason to use the generic type, just use `Program`.

Problem

I have a generic class Program with static method as below: ``` class Program { public static void Main() { Console.WriteLine("HI from program"); Console.ReadLine(); } } ``` When I try to access the static Main method inside a generic class Program1 as below: ``` class Program1<T> : Program where T : Program { public static void check() { T.Main(); } } ``` I get the error : 'T' is a 'type parameter', which is not valid in the given context However if I use ``` public static void check() { Program.Main(); } ``` Everything runs fine. Can you please explain the mistake that I might be committing?

Original source

Related problems