Erro CS8803 Top-level statements must precede namespace and type declarations - C#

asked 2023-01-09T23:54:57.56+00:00
Shervan360 1,011 Reputation points


I've created a Top-level statements project and pasted the below code:

class PetOwner  
    public string Name { get; set; }  
    public List<string> Pets { get; set; }  
public static void SelectManyEx3()  
    PetOwner[] petOwners =  
        { new PetOwner { Name="Higa",  
              Pets = new List<string>{ "Scruffy", "Sam" } },  
          new PetOwner { Name="Ashkenazi",  
              Pets = new List<string>{ "Walker", "Sugar" } },  
          new PetOwner { Name="Price",  
              Pets = new List<string>{ "Scratches", "Diesel" } },  
          new PetOwner { Name="Hines",  
              Pets = new List<string>{ "Dusty" } } };  
    // Project the pet owner's name and the pet's name.  
    var query =  
        .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })  
        .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))  
        .Select(ownerAndPet =>  
                    Owner = ownerAndPet.petOwner.Name,  
                    Pet = ownerAndPet.petName  
    // Print the results.  
    foreach (var obj in query)  


I got two errors and to solve these errors:
I moved the PetOwner class to a separate .cs file and remove the public keyword from the SelectManyEx3() method then disappeared errors.


My question is: Was there any other solution to solve these two errors?

Thank you

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,927 questions
No comments
{count} votes

Accepted answer
  1. answered 2023-01-10T00:18:40.077+00:00
    P a u l 7,566 Reputation points

    You could wrap your SelectManyEx3 definition inside a class Program { ... } definition and avoid using top-level statements, but if you do want to use them then the compiler makes the assumption that the code that you want to be put inside the generated class entry point (even with top-level statements there's always an entry class, you just don't see it) will be at the top of the file and all class definitions are after them, or in separate compilation units.

    No comments

0 additional answers

Sort by: Most helpful