Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 182 ยท Getting Started

C# Syntax

Learn the basic C# syntax - statements, blocks, case sensitivity, naming conventions, namespaces, using directives and how to read compiler error codes.

Every language has a grammar, and C# inherits a famous one: the "curly-brace" family shared by C, C++, Java and JavaScript. If you have written in any of them, much of this lesson will feel familiar. If you have not, do not worry: the rules are few and the compiler is helpful when you break one.

This lesson covers the pieces you will see in every file: statements and semicolons, blocks, case sensitivity, identifiers and naming conventions, namespaces and using directives, and how to read a compiler error so that it becomes a hint rather than a wall.

Statements and semicolons

A statement is one instruction. Most statements end with a semicolon. Statements run in order, top to bottom.

C# Statements run in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The semicolon is a statement terminator, not a separator or a line ending. Whitespace and newlines mean nothing to the compiler, so one statement may span many lines and many statements may sit on one line:

C#
int total = 10 +
            20 +
            30;                 // one statement on three lines
int a = 1; int b = 2;           // two statements on one line

Use that freedom to make code readable, not to be clever. The usual style is one statement per line, with long expressions wrapped after an operator.

An expression is anything that produces a value, such as width * height. Some expressions can be statements by themselves (a method call, an assignment, x++), but a bare width * height; is an error: the compiler wants every statement to do something, and reports error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

Blocks and scope

Curly braces { } group statements into a block. Blocks belong to if, loops, methods and types. A variable declared inside a block exists only inside that block (its scope).

C# Blocks create scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Un-commenting the last line produces error CS0103: The name 'inner' does not exist in the current context. A bare block is rare in real code, but the rule it shows is everywhere: names live in the block where you declare them, and an inner block can see the names of the blocks around it.

Brace style. The C# convention (and the one used here) is the Allman style: the opening brace goes on its own line, aligned with the keyword that owns it. Indentation is four spaces. The compiler does not care, but your teammates and the formatter do.

C#
if (area > 20)
{
    Console.WriteLine("Big");
}

Braces are optional for a single-statement body (if (x) Run();), but many teams require them always, because adding a second line later without adding braces is a classic source of bugs.

Case sensitivity

C# is case-sensitive. Name, name and NAME are three different identifiers, and keywords are all lowercase.

C# Case matters (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler says main.cs(2,19): error CS0103: The name 'Name' does not exist in the current context, plus a warning that name is assigned but never used. The variable is name, so Name is simply unknown. Similarly Console.writeline fails because the method is WriteLine. Case sensitivity is also why the naming conventions below matter: they let you tell a type from a variable at a glance.

Identifiers and naming conventions

An identifier is a name you give to a variable, method, type and so on. Rules:

  • letters, digits and underscores only, and it cannot start with a digit (score2 is fine, 2score is not);
  • it cannot be a reserved keyword such as class, int or if. You can force it with an @ prefix (@class), which is occasionally useful for interop but rarely a good idea;
  • Unicode letters are allowed (cafรฉ, ฯ€), though most teams stay with English ASCII names.

Conventions are not enforced by the compiler, but the whole .NET ecosystem follows them, so you should too:

Thing Style Example
Types: classes, structs, enums, records, delegates PascalCase Invoice, HttpClient
Interfaces I + PascalCase IDisposable, IReadOnlyList<T>
Methods, properties, events, constants PascalCase CalculateTotal, Count
Local variables and parameters camelCase totalPrice, userName
Private fields _camelCase _connection
Async methods end in Async LoadAsync
Generic type parameters T or TName T, TKey, TValue

Choose names that explain meaning: elapsedSeconds beats e, and customerCount beats n2. Abbreviations are fine only when universal (id, url).

C# Names that follow the conventions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You do not need to understand classes yet (Classes and Objects comes later). Just notice how the capitalization tells you what each name is. Notice also that the class is written after the statements that use it: in a file with top-level statements, type declarations must come last.

Namespaces and using directives

Thousands of types ship with .NET, and you will write many more. To avoid clashes (two different types both called Timer) and to organize code, C# groups types into namespaces. A type's full name is its namespace plus its own name: System.Collections.Generic.List<T>, System.IO.File, System.Text.StringBuilder.

Writing full names everywhere would be tiresome, so a using directive imports a namespace:

C# Full names versus using

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output is count=4. If you delete the using System.Text; line the program fails with error CS0246: The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?). That message is one of the most common you will ever see, and the fix is nearly always to add the right using.

Implicit usings

Modern projects (and our editor) enable implicit usings (C# 10): the compiler adds a set of global using directives for you, so you rarely write the common ones. They are System, System.Collections.Generic, System.IO, System.Linq, System.Net.Http, System.Threading and System.Threading.Tasks. That is why Console, List<T>, File and LINQ work with no using in the examples. In a real project you switch this on with <ImplicitUsings>enable</ImplicitUsings> in the .csproj, and you can add your own global using lines.

Two more using forms are worth knowing now:

C#
using Json = System.Text.Json.JsonSerializer;   // alias: a short local name
using static System.Math;                       // import a type's static members

With using static System.Math; you can write Sqrt(16) instead of Math.Sqrt(16). Use it sparingly, only where it makes formulas clearer.

Declaring a namespace

Your own types go in a namespace too. Since C# 10 you declare it with a file-scoped namespace, one line that applies to the whole file and saves a level of indentation:

C#
namespace Shop.Billing;      // file-scoped: everything below belongs to Shop.Billing

public class Invoice
{
}

The older block form still works and is common in older code:

C#
namespace Shop.Billing
{
    public class Invoice
    {
    }
}

A file may use only one style. Namespaces usually mirror folder names. In a multi-file project that gives you Shop.Billing.Invoice, and any other file can say using Shop.Billing; to reach it. In our single-file editor you can also use the block form, as long as it comes after the statements:

C# Our own namespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

typeof(Circle).FullName prints Geometry.Circle: the namespace is part of the type's identity. The Circle(double radius) form is a primary constructor; see Primary Constructors.

Reading compiler errors

Compiler messages follow a fixed pattern:

TEXT
main.cs(3,17): error CS1002: ; expected
^file   ^line,col  ^severity ^code    ^message
  • Position: line and column where the compiler noticed the problem. It is sometimes after the real cause. A missing semicolon is reported at the start of the next token, and an unclosed brace may be reported far below.
  • Severity: error stops the build; warning does not (but treat warnings seriously).
  • Code: CS plus a number. Search for it, and the documentation lists every cause.

Here are the five you will meet most often as a beginner:

Code Typical cause
CS1002 ; expected: a missing semicolon
CS0103 The name does not exist: a typo, wrong capitalization, or out of scope
CS0246 Type or namespace not found: a missing using or package
CS0029 Cannot implicitly convert one type to another
CS1501 / CS1503 Wrong number or type of arguments in a call
C# A missing semicolon (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports main.cs(1,27): error CS1002: ; expected. Look at the position: line 1, column 27 is the end of the first statement, which is exactly where the semicolon belongs. When the reported place looks odd, look at the line before.

When you see several errors, fix the first one and recompile. A single missing brace or semicolon can cascade into dozens of messages that vanish when you fix the cause.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What ends a statement in C#?

    C# uses the semicolon as the statement terminator. Newlines and indentation are only for human readers.
  2. 2. Which identifier follows the naming convention for a private field?

    Private fields are written _camelCase. PascalCase is for types, methods and properties; camelCase for locals and parameters.
  3. 3. string name = "Ada"; Console.WriteLine(Name); fails. Why?

    Identifiers are case-sensitive. The compiler reports CS0103 because no Name exists.
  4. 4. What does the file-scoped namespace namespace Shop.Billing; do?

    A file-scoped namespace (C# 10) applies to the whole file. It declares the namespace; a using directive is what imports one.
  5. 5. You get error CS0246: The type or namespace name 'StringBuilder' could not be found. What is the most likely fix?

    StringBuilder lives in System.Text, which is not among the implicit usings. A using directive (or the full name) fixes it.

Summary

  • Statements end with ;; whitespace and line breaks do not matter to the compiler.
  • Curly braces form blocks; names are visible only inside the block where they are declared (and in blocks nested in it).
  • C# is case-sensitive. Use PascalCase for types, methods and properties, camelCase for locals and parameters, and _camelCase for private fields.
  • Namespaces organize types; using imports them, and implicit usings add the common ones for you.
  • File-scoped namespaces (namespace A.B;, C# 10) save one level of indentation.
  • Compiler messages give file, line, column, severity and a CS code; the real cause is sometimes just before the reported position.

Next: Program Structure: Top-Level Statements and Main shows how a C# program starts and ends.