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.
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:
Consoleandconsoleare different names;Mainmust 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:
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.
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:
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#?
- .
- :
- ;
- Nothing — line breaks end statements
Is C# case-sensitive?
- Yes
- No
- Only for keywords
- Only for class names
Which naming style is conventional for C# method names?
- snake_case
- camelCase
- PascalCase
- UPPER_CASE