Your first program
Learn to write your first C# program with the Main method, namespaces and using.
The Main method
The place where C# programs start is called the Main method. When the program runs, the code inside Main executes first.
A Main method looks like this:
static void Main(){
// code here
}To print a line to the screen you use Console.WriteLine. WriteLine automatically moves the cursor to a new line after printing.
using and namespace
The using directive brings a namespace into your program. The most common one is using System;
namespace groups related classes together. A program skeleton looks like this:
using System;
namespace HelloApp
{
class Program
{
static void Main()
{
Console.WriteLine("Hello");
}
}
}This structure keeps code organized.
Exercise Write your first program
Add a Console.WriteLine line below the Print the message comment. The output must be Hello World.
Show example solution
Add a Console.WriteLine line below the comment.
Example solution:
using System;
class Program
{
static void Main()
{
// Print the message
Console.WriteLine("Hello World");
}
}
Test yourself
-
What is the entry point of a C# program?
- The Main method
- The Start method
- The Run method
- The Init method
Show answer
The Main method — Correct! The Main method is where the program starts.
-
Method of the Console class
Console.____("Hello World");Show answer
Console.WriteLine("Hello World"); -
Match the keyword to its role
- using
- Imports a namespace
- namespace
- Declares a namespace
- class
- Declares a class
- Main
- Entry point