Utilizor
Contact Us

C# Syntax

Understanding C# syntax rules.

C# Syntax

A C# program is made up of different parts. Let's study the following code:

Example Explained

  • using System; means that we can use classes from the System namespace.
  • namespace HelloWorld is a container for classes and other namespaces.
  • class Program is a container for data and methods, which brings functionality to your program. Every line of code that runs in C# must be inside a class.
  • static void Main(string[] args) is the entry point of your C# application.
  • Console.WriteLine("Hello World!"); is a method of the Console class (system namespace) that outputs/prints text.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

Examples

Basic Syntax

Standard structure of a C# program.

using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");
    }
  }
}

Case Sensitivity

Demonstrating variable names are case sensitive.

using System;

class Program
{
    static void Main(string[] args)
    {
        int myVar = 10;
        // int MyVar = 20; // This would be a different variable
        Console.WriteLine(myVar);
    }
}

Using Block

Code blocks are defined by curly braces.

using System;

class Program {
  static void Main(string[] args) {
    Console.WriteLine("Blocks use curly braces {}");
  }
}

Semicolons

Statements must end with a semicolon.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Statement 1");
        Console.WriteLine("Statement 2");
    }
}

Comments

Comments are part of the syntax but ignored by compiler.

using System;

class Program
{
    static void Main()
    {
        // This is a comment
        Console.WriteLine("Comments are ignored");
    }
}