C# Syntax

Basic Program Structure

A C# program typically includes:

  • using directives for namespaces
  • These import namespaces to give your program access to predefined classes and functions.

  • A namespace declaration
  • Organizes your code and prevents naming conflicts by grouping related classes together. Not necessary, but recommended in complex and high-level programs

  • A class declaration
  • Defines a blueprint for objects and contains the program’s data and methods.

  • A Main method where execution begins
using System;

namespace HelloWorld {
    class Program {
        static void Main() {
            Console.WriteLine("Hello, world!");
        }
    }
}

The Main Method

Every C# application must have a Main method, which is the entry point of the program.

Statements and Semicolons

Every statement in C# must end with a semicolon (;).

Curly Braces

C# uses { } to group code blocks, such as in methods, conditionals, and loops.

using System;

namespace ExampleNamespace {
    class Program {
        static void Main(string[] args) {
            int number = 5;
            if (number > 0) {
                Console.WriteLine("Positive number");
            }

            for (int i = 0; i < 3; i++) {
                Console.WriteLine("Loop iteration: " + i);
            }
        }
    }
}

Printing to the Console

In C#, you use Console.WriteLine() to print output to the console with a newline, and Console.Write() to print without a newline.

Example using WriteLine():

Loading...
Output:

Example using Write():

Loading...
Output:

Comments

Use comments to describe your code:

// This is a single-line comment

/* This is
a multi-line comment */

Case Sensitivity

C# is case-sensitive: value and Value are different identifiers.

Practice Prompt

What’s wrong with this program?

using System;
class Program {
    static void main() {
        console.WriteLine("Oops");
    }
}

If you are stuck or need help, use the AI chatbot

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic