Using static void Main() method from base class as a program's entry point

2.8k views Asked by At

I would like to abstract some program logic to a base class for executing a command-line program (functionality similar to what this question was requesting).

in other words, something like this:

public abstract class BaseProgram<T>
{
    public static void Main(string[] args)
    {
        Console.WriteLine(typeof(T));
    }
}

public class Program : BaseProgram<string>
{
}

It is important to note that BaseProgram is in a different assembly.

This, however, does not work. The static void Main(string[] args) method must be in the derived class. Can anyone explain why that is? After all, the following is totally 'legal':

Program.Main(null);
BaseProgram<string>.Main(null);

and will output:

> System.String
> System.String

What I would like to know: are there any documented reasons for this outcome?

2

There are 2 answers

0
Peter Duniho On BEST ANSWER

As was eventually disclosed during the commenting of the other answer, your BaseProgram<T> class is in a different assembly from the one you are trying to execute. The entry point of an assembly has to be in that assembly.

To do otherwise is like giving someone a key and telling them that's the key to your house's front door. Except the key is actually for some other completely different house's front door, so when they show up at your house it does them no good.

If you want to use the BaseProgram<T>'s Main() method, you need to delegate to it. For example, in your own assembly:

static class Program
{
    public static int Main(string[] args)
    {
        return BaseProgram<string>.Main(args);
    }
}

Note that for static types or static members of types, there's no need to actually inherit the base type, since you just invoke it via the actual type name instead of an instance reference.

8
Selman Genç On

I think the problem is that BaseClass is generic. In order to call main you have to supply a type argument, so which type should the system choose to call this method? Ofcourse it can't make random choices so this is illegal.

I found this in C# 5.0 Language Specification in 3.1 Application Startup

The application entry point method may not be in a generic class declaration.