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");
}
}
ThisShouldBeAMethodOfProgramClass
method is just a local method that cannot be accessed by other code. – Lean