简体   繁体   中英

What are top level statements in C#? What is their use?

I just created my first .NET 6 console app, and instead of the default,

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

I got:

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

And even when there's no class, the program runs, I took a look at the link provided in the comments. but I don't know if this is a new feature or an old one, If this is a new feature? does that mean C# will be allowing C-style programming hereafter?

It's a new feature of C# 9 or 10. Microsoft documentation says following:

Top-level statements enable you to avoid the extra ceremony required by placing your program's entry point in a static method in a class. The typical starting point for a new console application looks like the following code:

using System;

namespace Application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

The preceding code is the result of running the dotnet new console command and creating a new console application. Those 11 lines contain only one line of executable code. You can simplify that program with the new top-level statements feature. That enables you to remove all but two of the lines in this program:

Console.WriteLine("Hello, World!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM