Search code examples
c#methodstoplevel-statement

How to define a method following top-level statements


I recently updated Visual Studio and found out about this new feature (to me it is new) of top-level statements.

As I understand it, the compiler completes the definitions for the Program class and Main method, without you having to explicitly type it up.

This is useful, but I'm having trouble when defining a new method. I would like a method in the Program class. And call this with a top-level statement. Here is some example code:

Console.WriteLine("toplevel");
ThisShouldBeAMethodOfProgramClass();

public static void ThisShouldBeAMethodOfProgramClass()
{
    Console.WriteLine("Static in Program class");
}

This is giving me build errors, because the public static modifiers are not valid. I think it interprets this as a local function in Main. I can remove the modifiers, but this is just example code, my real code has more methods and classes.

How can I do this? Should I not use top-level for this?

I would like this to effectively be the same as:

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("toplevel");
        ThisShouldBeAMethodOfProgramClass();
    }
    public static void ThisShouldBeAMethodOfProgramClass()
    {
        Console.WriteLine("Static in Program class");
    }
}

Solution

  • You can keep using top-level statements and append additional members with a partial Program class.

    using System;
    Console.WriteLine("toplevel");
    ThisShouldBeAMethodOfProgramClass();
    
    public static partial class Program
    {
        public static void ThisShouldBeAMethodOfProgramClass()
        {
            Console.WriteLine("Static in Program class");
        }
    }