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

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

Hello,

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 =  
        petOwners  
        .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })  
        .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))  
        .Select(ownerAndPet =>  
                new  
                {  
                    Owner = ownerAndPet.petOwner.Name,  
                    Pet = ownerAndPet.petName  
                }  
        );  
  
    // Print the results.  
    foreach (var obj in query)  
    {  
        Console.WriteLine(obj);  
    }  
}  
  

277550-screenshot-2023-01-09-154747.png

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.

277633-screenshot-2023-01-09-155401.png

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

Thank you

C#
C#
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.
10,190 questions
0 comments No comments
{count} votes

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

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful