1

I recently tried the .Net 6 console template, with top level statements, in Visual studio and stumbled into a Gotcha. If you try to compile the below code, Visual Studio will give a red squiggly line under the string declaration var s = "myString";. You will also receive the error: Top-level statements must precede namespace and type declarations.

delegate string StringReturner(int i);

var s = "myString";
Console.WriteLine(s); 

So, what is the problem here?

FluffyBike
  • 825
  • 1
  • 4
  • 17

1 Answers1

1

The issue is that the delegate declaration has to happen after the top level statements. A delegate declaration does not count as a top level statement, but counts as a type declaration. The following code works fine:

var s = "myString";
Console.WriteLine(s);

delegate string StringReturner(int i);
FluffyBike
  • 825
  • 1
  • 4
  • 17