June 24, 2023

C# - top level instructions

I am a total beginner. Using visual studio and selecting "console application" I have been surprised to see the code to be a single executable line:
Console.WriteLine("Hello World!");

What is going on here? How can this possibly be valid code? To make a long story short, this is using a new (as of C# 9) feature called "top level statements". You may have noticed that Visual Studio offered a check box saying "don't use top level statements".

The idea is that this makes quick experiments easy to do. Only one file can contain top level statements. The normal way to do business would be:

using System;

namespace Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
And presumably this is what you would have gotten if you had checked that checkbox and told visual studio to not use top level statements.
Feedback? Questions? Drop me a line!

Tom's Computer Info / tom@mmto.org