Where to define delegates in .Net 6 Console template using top level statements?

624 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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);