"Wrap top level statements into class" or "Move top-level statements before namespaces"

165 Views Asked by At

I'm trying to have a more in-depth understanding of coding with the C# language. And so I am trying to dissect every suggestion from IDEs.

The two screenshots below show the two different scenarios of creating an instance of a class. As you can see, one of the suggestions creates an error. So I'm trying to understand, in principle, what are the differences between using the two methods shown below. What advantage or disadvantage, if any, occurs when writing a complex game or a program script?

enter image description here

enter image description here

Spaceship myShip = new Spaceship();

public class Spaceship
{
    // Instance Variables //
    public string callSign;
    private int shieldStrength;
    
    // Methods //
    public string fireMissile()
    {
        return "Pew pew!";
    }

    public void reduceShield(int amount)
    {
        shieldStrength -= amount;
    }
   
}

class Program
{
    public static void Main(string[] args)
    {
        Spaceship herShip = new Spaceship();
    }
}
1

There are 1 best solutions below

3
On BEST ANSWER

On the second screen you have method Main (classic way of entry point of app in c#) and a top-level statement (.NET 6 syntax-sugar for Main method without explicitly writing it). So you have mixed two different approaches. Compiler does not know which entry-point he should choose (you cannot enter both different doors at the same time).

Decide between Main method inside Program class or top-level statement. Don't use both.