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

  1. 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.
  2. namespace HelloWorld
    This line declares a namespace called HelloWorld. Namespaces are used to organize code into a logical grouping.
  3. class Program
    This line declares a class named Program. In C#, all programs must define at least one class.
  4. static void Main(string[] args)
    This line defines the Main method, which is the entry point of a C# program. The static keyword means that this method can be called without an instance of the class. void means the method does not return a value.
  5. {
    This opening brace marks the beginning of the Main method's body.
  6. Console.WriteLine("Hello, World!");
    This line prints the string "Hello, World!" to the standard output (usually the screen).
  7. }
    This closing brace marks the end of the Main method's body.
  8. }
    This closing brace marks the end of the Program class's body.
  9. }
    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 and main would be considered different identifiers.