C# Error CS8803 – Top-level statements must precede namespace and type declarations.

C# Error

CS8803 – Top-level statements must precede namespace and type declarations.

Reason for the Error & Solution

Top-level statements must precede namespace and type declarations.

Example

The following sample generates CS8803:

// CS8803.cs (0,0)

public record Person
{
    public string? GivenName { get; set; }
    public string? FamilyName { get; set; }
}

int i = 0;

In a file with top-level statements, top-level statements must occur prior to any type declarations.

To correct this error

Move the code before the namespace declaration:


int i = 0;

public record Person
{
    public string? GivenName { get; set; }
    public string? FamilyName { get; set; }
}

It is common that types are declared within their own file, which would also correct this error by separating the type declaration from the top-level statements.