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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...