0

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();
    }
}
Sevcan D.
  • 53
  • 9

1 Answers1

1

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.

  • Thank you so much for your answer Dawid Łazuk. I understand the differences between the two methods now. In your opinion, is there any benefit to using either one of these when writing a long script? – Sevcan D. Dec 23 '22 at 10:29
  • IMO doesn't matter. In case of the top-level statement the compiler will generate the Main method itself and it will be present in the IL (intermediate language). One advantage of the direct Main method is forward-compatibility - in case you would have to migrate to older .NET versions which does not support top-level statements you won't have to rewrite it - IMO rare case. Most of the projects are split into classes so you won't spend a lot of time in the entry class. – Dawid Łazuk Dec 23 '22 at 10:42
  • Hello again. I apologize for the late reply and thank you so much for your detailed explanation. I definitely appreciate these types of answers since as I said, I'm trying to get a more in-depth understanding of the language. – Sevcan D. Dec 24 '22 at 14:09