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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...