C# Syntax Fundamentals

Identifiers name variables, methods, classes, properties, namespaces, interfaces and constants.

Concept

Identifiers name variables, methods, classes, properties, namespaces, interfaces and constants.

They contain letters, digits and underscores, and cannot start with a digit.

They are case-sensitive: speed and Speed are different.

Keywords cannot be used as identifiers unless prefixed with @ (a *verbatim identifier*, e.g. @class).

Naming conventions: PascalCase for types, methods, properties, constants and namespaces; camelCase for locals and parameters; _camelCase for private fields; interfaces start with I (IEngine).

C# has reserved keywords (always keywords) and contextual keywords (keywords only in specific positions).

class, struct, record, interface, enum, delegate

public, private, protected, internal static, readonly, const, abstract, virtual, override, sealed, unsafe ref, out, in, params Async / iterators async, await, yield checked, unchecked Resource / threading using, lock, fixed

var, dynamic, record, init, required, when, get, set, value, field Statements and Expressions

An expression computes a value: speed + 5, total > 150, x ? "a" : "b", a method call returning a value.

A statement performs an action and ends with ; (or is a block): declarations, assignments, method calls, if, loops, return.

A block { ... } groups statements and creates a scope: variables declared inside are not visible outside.

Operators combine expressions (Module 7); method calls can be expressions (when they return a value) or statements.

Semicolons and Braces Every simple statement ends with a semicolon. Braces delimit blocks, type bodies and method bodies. Whitespace and line breaks are not significant (unlike Python), but consistent formatting (4 spaces, Allman braces on new lines) is the.NET convention.

Why It Matters

Syntax errors are the first thing every beginner meets; reading compiler errors quickly (CS1002 ; expected, CS0103 name does not exist, CS0029 cannot convert) saves hours.

Syntax

type identifier = expression;   // declaration statement
identifier = expression;        // assignment statement
Method(arguments);              // call statement
{ statement; statement; }       // block

Example

// Identifiers: letters, digits, underscore; cannot start with a digit; case-sensitive.
int speed = 120;
int Speed = 80;            // a different variable: identifiers are case-sensitive
int _counter = 1;
int @class = 5;            // '@' lets you use a keyword as an identifier (verbatim identifier)
Console.WriteLine($"speed={speed}, Speed={Speed}, _counter={_counter}, @class={@class}");

// Expressions produce values; statements perform actions.
int total = speed + Speed;                  // declaration statement containing an expression
bool isFast = total > 150;                  // relational expression
string label = isFast ? "fast" : "slow";   // conditional expression
Console.WriteLine($"total={total}, isFast={isFast}, label={label}");

// A block groups statements and creates a scope.
{
    int inner = total * 2;
    Console.WriteLine($"inside block: inner={inner}");
}
// 'inner' is not visible here.

// Contextual keywords (var, record, async, when...) are only keywords in certain positions:
int var = 3;               // legal, but confusing - avoid in real code
Console.WriteLine($"var={var}");

Expected Result

speed=120, Speed=80, _counter=1, @class=5
total=200, isFast=True, label=fast
inside block: inner=400
var=3

Common Mistakes

A missing semicolon — real compiler output:

Wrong case and wrong type — real compiler output:

Other frequent errors: unmatched braces (CS1513 } expected), using a variable outside its block (CS0103), and using a keyword as a name (CS1041).

int count = 10;
Console.WriteLine(count)
Console.WriteLine("done");
m04_err.cs(2,25): error CS1002: ; expected
string name = "ECU";
Console.WriteLine(Name);        // identifiers are case-sensitive
int speed = "fast";              // a string is not an int
Console.WriteLine(speed);
m04_err2.cs(2,19): error CS0103: The name 'Name' does not exist in the current context
m04_err2.cs(3,13): error CS0029: Cannot implicitly convert type 'string' to 'int'

Best Practices

Follow .NET naming conventions consistently; let the IDE and .editorconfig enforce them.

Keep one statement per line and use blocks even for one-line if bodies.

Read the error code (e.g. CS1002): searching for it finds the documentation immediately.

Avoid naming variables after contextual keywords (var, record) even though it is legal.

Interview Relevance

Low: usually tested indirectly through coding exercises; naming conventions and "statement vs expression" occasionally come up.

Practice Questions

Which of these identifiers are valid: 2fast, _speed, speedKmh, class, @class, max-rpm?

Classify as statement or expression: x + 1, x = x + 1;, Console.WriteLine(x);, x > 3.

Fix the two programs in Common Mistakes.

Write a block that declares a variable, and try to use it after the block. What error do you get?

Quick Quiz

Q1. (True/False) Total and total refer to the same variable.

Answer: False. C# is case-sensitive.

Q2. (Multiple choice) How do you use the keyword event as a variable name? A) _event B) @event C) event_ D) It is impossible

Answer: B. @event is a verbatim identifier (A and C are simply different names).

Q3. (Find the bug) Console.WriteLine("ok") followed by another statement on the next line gives CS1002. Why?

Answer: The first statement is missing its terminating semicolon.

Q4. (Predict the output) int a = 3; { int b = a * 2; } Console.WriteLine(b);

Answer: It does not compile: b is out of scope after the block (CS0103).

Coding Challenge

Declare variables for a vehicle's model name, model year and top speed, compute whether the car is "new" (year ≥ 2024) and print a one-line summary.

string model = "Aurora EV";
int modelYear = 2025;
int topSpeedKmh = 190;
bool isNew = modelYear >= 2024;
Console.WriteLine($"{model} ({modelYear}), top speed {topSpeedKmh} km/h, new: {isNew}");