C# Syntax

C# syntax is the set of rules that tells the compiler how your program is written. It covers where code goes, how statements end, how blocks are grouped, how names are spelled, and how the compiler turns text into executable instructions. Learning syntax well matters because C# is precise: a missing semicolon, a lowercase keyword in the wrong place, or a block in the wrong scope changes what the program means or prevents it from compiling.

Overview: How C# Syntax Works

A C# program is plain text source code that is compiled before it runs. The compiler reads your files, checks the grammar of the language, checks the types used by each expression, and produces an assembly that the .NET runtime can execute. The runtime, commonly called the CLR, loads that assembly, starts the entry point method, manages memory for objects, and runs the compiled instructions.

Most beginner C# programs have a few major parts: optional using directives, a class, a Main method, statements inside the method, and expressions inside those statements. A using directive makes a namespace easier to use. A class is a type that groups methods and data. The Main method is the entry point where execution begins. A statement is a complete instruction, usually ending with a semicolon. An expression is a piece of code that produces a value, such as 3 + 4, name, or score >= 70.

C# is case-sensitive. Console, console, and CONSOLE are three different names. Keywords such as class, static, void, if, and return must be written exactly. Whitespace is usually flexible, so indentation does not change meaning the way it does in some languages, but good indentation makes scope visible to humans.

Blocks are written with braces: { and }. A block creates a region of code for a class, method, loop, or conditional branch. Variables declared inside a block are usually scoped to that block, meaning code outside the block cannot use them. This is one of the most important syntax ideas in C#: braces do not merely decorate the code; they define where names exist and which statements belong together.

Syntax

The common shape of a simple C# program is:

using System;

class Program
{
    static void Main()
    {
        // statements go here
        Console.WriteLine("Hello");
    }
}
Part Meaning
using System; Allows code to refer to types in the System namespace, such as Console, without writing the full namespace every time.
class Program Declares a class named Program. In these lessons, runnable examples use this class as the container for the entry point.
{ ... } Creates a block. Blocks group declarations and statements and determine scope.
static void Main() Declares the entry point method. static means it belongs to the class itself, void means it returns no value, and Main is the method the runtime starts.
Console.WriteLine(...); A statement that calls a method and ends with a semicolon.
// comment A single-line comment ignored by the compiler.

Statements normally end with semicolons. Declarations that introduce blocks, such as class, if, for, and method declarations, use braces instead of ending the block header with a semicolon.

Examples

A Minimal Program With Variables

using System;

class Program
{
    static void Main()
    {
        string language = "C#";
        int firstReleaseYear = 2000;

        Console.WriteLine("Language: " + language);
        Console.WriteLine($"First released: {firstReleaseYear}");
    }
}

Output:

Language: C#
First released: 2000

This program declares two local variables inside Main. The first is a string, which stores text. The second is an int, which stores a whole number. The first output line uses string concatenation with +. The second uses string interpolation, where values inside { and } are evaluated and inserted into the string.

Blocks, Conditions, and Loops

using System;

class Program
{
    static void Main()
    {
        int score = 87;
        bool passed = score >= 70;

        if (passed)
        {
            Console.WriteLine("Result: pass");
        }
        else
        {
            Console.WriteLine("Result: try again");
        }

        for (int attempt = 1; attempt <= 3; attempt++)
        {
            Console.WriteLine($"Attempt {attempt}");
        }
    }
}

Output:

Result: pass
Attempt 1
Attempt 2
Attempt 3

The if statement chooses between two blocks. Because score >= 70 evaluates to true, the first block runs. The for statement has three syntax parts inside parentheses: initialize attempt, keep looping while the condition is true, and update attempt after each iteration.

Methods and Return Values

using System;

class Program
{
    static void Main()
    {
        string name = "Mina";
        int minutes = 42;

        Console.WriteLine(BuildStatus(name, minutes));
        Console.WriteLine(BuildStatus("Ravi", 5));
    }

    static string BuildStatus(string student, int minutesStudied)
    {
        if (minutesStudied >= 30)
        {
            return $"{student}: full practice session";
        }

        return $"{student}: quick review";
    }
}

Output:

Mina: full practice session
Ravi: quick review

This example adds a second method. Its syntax says that BuildStatus is static, returns a string, and requires two parameters. A return statement sends a value back to the caller and exits the method. The compiler checks that every possible path through this method returns a string.

How It Works Step by Step

When you build a C# program, the compiler first tokenizes the source text into meaningful pieces: keywords, identifiers, literals, punctuation, and operators. It then parses those tokens according to the C# grammar. For example, int score = 87; is parsed as a local variable declaration, while Console.WriteLine(score); is parsed as a method call statement.

After parsing, the compiler performs semantic checks. It verifies that names exist in the current scope, that operators are valid for the involved types, that methods receive the right arguments, and that assignments are type-safe. This is why int score = "high"; fails: the syntax shape is understandable, but the meaning is invalid because a string cannot be assigned to an int without conversion.

If compilation succeeds, the compiler emits intermediate language and metadata into a .NET assembly. At runtime, the CLR loads the assembly, finds Program.Main, and begins executing instructions. Local variables such as score live for the duration of their scope. Objects such as strings are managed by the runtime, and memory that is no longer reachable can be reclaimed by the garbage collector.

Common Mistakes

Missing Semicolons

int count = 3
Console.WriteLine(count);

This does not compile because the first statement never ends. C# uses semicolons to separate many statements, so the compiler cannot reliably understand where the declaration stops.

int count = 3;
Console.WriteLine(count);

Output:

3

Wrong Capitalization

string course = "C#";
console.WriteLine(course);

This fails because console is not the same identifier as Console. The .NET type is named with an uppercase C.

string course = "C#";
Console.WriteLine(course);

Output:

C#

Putting Code Outside a Method

In the explicit class style used in this course, executable statements belong inside a method such as Main. A class body can contain fields, methods, properties, constructors, and nested types, but not ordinary statements floating by themselves.

Best Practices

  • Use clear indentation so every block’s start and end are visible.
  • Name variables with meaningful camelCase names, such as firstReleaseYear instead of x.
  • Use PascalCase for class and method names, such as Program and BuildStatus.
  • Keep one statement per line unless there is a strong readability reason to do otherwise.
  • Prefer string interpolation for readable formatted output.
  • Place related statements close together, and move repeated logic into methods.
  • Read compiler errors from top to bottom; one syntax error can cause several later messages.
  • Use comments to explain intent or unusual decisions, not to repeat what the code visibly says.

Practice Exercises

  1. Write a program that stores your name and favorite number in variables, then prints both values on separate lines.
  2. Write a program with an int temperature variable. If it is at least 30, print Hot day; otherwise print Mild day.
  3. Create a method named DescribeScore that accepts an int and returns Pass when the score is 70 or higher, otherwise Review.

Summary

  • C# syntax is the grammar that lets the compiler understand your program.
  • Runnable programs in this course use a Program class with a static void Main() entry point.
  • Most statements end with semicolons, while blocks are grouped with braces.
  • C# is case-sensitive, so spelling and capitalization matter.
  • The compiler checks both syntax and meaning before the CLR runs your code.
  • Good formatting does not usually change execution, but it makes scope, flow, and mistakes much easier to see.