Basic Syntax
Let’s learn the basic syntax of C# by following a simple “Hello World” example.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Output:
Hello World!
- using System;: This line allows us to use classes from the System namespace.
- namespace HelloWorld: Namespaces organize your code and act as containers for classes and other namespaces.
- class Program: A class is a container for data and methods, providing functionality to your program. Every line of C# code must be inside a class.
- static void Main(string[] args): The Main method is where your program starts executing. Any code inside its curly braces {} will be executed.
- Console.WriteLine(“Hello World!”);: This line uses the Console class from the System namespace to output “Hello World!”.
Remember these key points:
- Every C# statement ends with a semicolon ;.
- C# is case-sensitive, so “MyClass” and “myclass” have different meanings.
- The name of the C# file doesn’t have to match the class name, but it often does for better organization.
