Basic Syntax in C#
In this tutorial, we will learn the basic syntax of C# language. We will go through the key components of a simple C# program.
C# Program
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Output
Hello, World!
Basic Syntax of a C# Program
using System;
This line includes the System namespace, which contains fundamental classes and base classes that define commonly-used values and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.namespace HelloWorld
This line declares a namespace called HelloWorld. Namespaces are used to organize code into a logical grouping.class Program
This line declares a class named Program. In C#, all programs must define at least one class.static void Main(string[] args)
This line defines the Main method, which is the entry point of a C# program. Thestatic
keyword means that this method can be called without an instance of the class.void
means the method does not return a value.{
This opening brace marks the beginning of the Main method's body.Console.WriteLine("Hello, World!");
This line prints the string "Hello, World!" to the standard output (usually the screen).}
This closing brace marks the end of the Main method's body.}
This closing brace marks the end of the Program class's body.}
This closing brace marks the end of the HelloWorld namespace's body.
Key Points to Remember
- All C# statements must end with a semicolon (
;
). - The Main method is the entry point of a C# program.
- Comments can be added using
//
for single-line comments or/* ... */
for multi-line comments. - Code blocks are enclosed in curly braces
{}
. - The
using
directive is used to include the namespaces in the program. - C# is case-sensitive, meaning that
Main
andmain
would be considered different identifiers.