Search code examples
delegates.net-6.0toplevel-statement

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


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?


Solution

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