TExcelTAD
Home › C# › C# Syntax

C# Syntax

C# code is made of statements that live inside methods, which live inside types (classes, structs, records…), which are usually organised into namespaces. Let's take a classic program apart line by line.

csharp · try it yourself
using System;

namespace MyFirstApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Learning C# syntax");
        }
    }
}
Learning C# syntax
Line Meaning
using System; Import the System namespace so we can write Console
namespace MyFirstApp Group our types under a name to avoid clashes with other code
class Program Declare a class; every method must belong to a type
static void Main() The entry point: static (no object needed), void (returns nothing)
Console.WriteLine(...) Call the WriteLine method of the Console class

Rules to remember

  • Every statement ends with a semicolon ;.
  • Curly braces { } mark the start and end of a block of code (a namespace, class, method, loop…).
  • C# is case-sensitive: Console and console are different names; Main must be spelled with a capital M.
  • Whitespace does not matter to the compiler, but consistent indentation makes code readable.
  • The file name does not have to match the class name (unlike Java), although it is a good convention.

Because whitespace is ignored, these two statements are identical to the compiler:

csharp · try it yourself
using System;

Console.WriteLine("one line");
Console
    .WriteLine(
        "spread over four lines");
one line
spread over four lines

File-scoped namespaces

Since C# 10 you can declare a namespace for the whole file with a single line ending in a semicolon. This saves one level of indentation and is the style most modern code uses.

csharp · try it yourself
using System;

namespace Shop.Billing;

class Program
{
    static void Main()
    {
        Console.WriteLine("Namespace: " + typeof(Program).Namespace);
    }
}
Namespace: Shop.Billing

Naming conventions

C# has strong community conventions. Following them makes your code look "native":

Kind of name Convention Example
Classes, methods, properties PascalCase OrderService, CalculateTotal
Local variables, parameters camelCase itemCount, firstName
Private fields _camelCase _balance
Interfaces I + PascalCase IComparable
Constants PascalCase MaxRetries

A common mistake

Forgetting a semicolon is the classic beginner error. The compiler stops and reports error CS1002: ; expected:

csharp
using System;

Console.WriteLine("missing semicolon")

Tip: Read compiler errors from the top. The first error is usually the real problem; later ones are often side effects.

Test yourself

What character ends a statement in C#?

  1. .
  2. :
  3. ;
  4. Nothing — line breaks end statements

Is C# case-sensitive?

  1. Yes
  2. No
  3. Only for keywords
  4. Only for class names

Which naming style is conventional for C# method names?

  1. snake_case
  2. camelCase
  3. PascalCase
  4. UPPER_CASE