What does
using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ["using System"] mean? Why can't you start your code without these lines?
35 Answers
The using System line means that you are using the System library in your project. Which gives you some useful classes and functions like Console class or the WriteLine function/method.
The namespace ProjectName is something that identifies and encapsulates your code within that namespace. It's like package in Java. This is handy for organizing your codes.
class Program is the class name of your entry-point class. Unlike Java, which requires you to name it Main, you can name it whatever in C#.
And the static void Main(string[] args) is the entry-point method of your program. This method gets called before anything of your program.
And you can actually write a program without some of them in DotNet 5 and later as it now supports top level functions.
1It includes the namespace to that you can accesses classes within it more easily. You can write code without it but you would always have to explicitly state it any time you use it like System.Console.WriteLine("Hello World");.
Read up on namespaces here
Every program has an entry point (The first method to be called when your program is executed) Main method is the entry point of the program you are creating.
In .NET classes are organized in namespaces, there are classes that come with the framework (built-in) that assists us with printing output, accessing the file system etc. The classes within the namespaces can be accessed using the using keyword.
For instance:
To print an output we need to access the system namespace which contains the Console class that has Writeline method. Hence the use of using system
We have namespaces in C# which we use to organize classes and the system is a namespace in C#. using system; imports the namespace and you can now access the classes in the System namespace, without the line using namespacename you cannot access the classes within it. console is one of the classes in the System namespace.
It's the way that .NET Framework, .NET Core and similar C# versions define the way a program should label the start of their program.
This is called an Entry Point and must meet certain signature requirements for any C# Version < 9.0.
// tells the compiler what functions, such as Console.WriteLine that // you're going to use or should import using System; // defines a class, can be named anything class Program { // defines an entry point for your program // must be named Main and meet certain signature requirements public static void Main() { Console.WriteLine("Hello World!"); } } As of .NET 5.0(C# 9.0) (the latest version) you don't actually have to use this format and can just use Top Level code that's not wrapped in a class, and the compiler will assume that's the entry point for your program such as:
using System; Console.WriteLine("Hello World!");