Learnixo
Back to blog
Backend Systemsbeginner

C# Syntax Explained — Complete Beginner Reference

A comprehensive beginner reference for C# syntax: types, operators, control flow, methods, string handling, and common pitfalls with clear code examples.

Asma Hafeez KhanMay 24, 20266 min read
csharpdotnetbeginnersyntaxreference
Share:𝕏

C# Syntax Explained — Complete Beginner Reference

This guide covers every core syntax element you need to read and write C# confidently. Use it as a reference when a keyword or construct is unfamiliar.


Types and Variables

C#
// Value types — stored on the stack
int    age     = 30;
double price   = 9.99;
decimal tax    = 0.20m;   // m suffix for decimal literals
bool   isOpen  = true;
char   letter  = 'A';

// Reference types — stored on the heap
string name    = "Alice";
object anything = 42;

// Type inference — compiler deduces the type
var count  = 100;       // int
var pi     = 3.14;      // double
var label  = "hello";   // string

// Constants — set once, never change
const int MaxRetries = 3;
const string AppName = "SystemForge";

Nullable Types

C#
// Nullable value types — can be null
int?    nullableInt  = null;
double? nullableRate = null;

if (nullableInt.HasValue)
    Console.WriteLine(nullableInt.Value);

// Null-coalescing: return default if null
int count = nullableInt ?? 0;

// Nullable reference types (C# 8+, enable in .csproj)
string? maybeNull = null;   // explicitly nullable
string  notNull   = "hi";   // compiler warns if you assign null here

Operators

C#
// Arithmetic
int sum  = 10 + 3;   // 13
int diff = 10 - 3;   // 7
int prod = 10 * 3;   // 30
int quot = 10 / 3;   // 3  (integer division truncates)
int rem  = 10 % 3;   // 1  (remainder / modulo)

// Comparison — always returns bool
bool eq  = 5 == 5;   // true
bool neq = 5 != 4;   // true
bool gt  = 5 > 3;    // true

// Logical
bool and  = true && false;   // false (short-circuits)
bool or   = true || false;   // true  (short-circuits)
bool not  = !true;           // false

// Assignment shortcuts
int x = 10;
x += 5;    // x = 15
x -= 2;    // x = 13
x *= 2;    // x = 26
x /= 2;    // x = 13

// Null-conditional (C# 6+)
string? s = null;
int? len = s?.Length;   // null instead of NullReferenceException

// Null-coalescing assignment (C# 8+)
string? label = null;
label ??= "default";   // assigns "default" only if label is null

Control Flow

if / else if / else

C#
int score = 75;

if (score >= 90)
    Console.WriteLine("A");
else if (score >= 70)
    Console.WriteLine("B");
else
    Console.WriteLine("C or below");

switch expression (C# 8+)

C#
string grade = score switch
{
    >= 90 => "A",
    >= 70 => "B",
    >= 50 => "C",
    _      => "F",   // default arm
};

Classic switch statement

C#
switch (score)
{
    case 100:
        Console.WriteLine("Perfect");
        break;
    case >= 90 and < 100:
        Console.WriteLine("Excellent");
        break;
    default:
        Console.WriteLine("Keep going");
        break;
}

Loops

C#
// for — use when you know the number of iterations
for (int i = 0; i < 5; i++)
    Console.WriteLine(i);   // 0 1 2 3 4

// while — use when the stop condition is evaluated each iteration
int n = 0;
while (n < 3)
{
    Console.WriteLine(n);
    n++;
}

// do-while — body always executes at least once
do
{
    Console.WriteLine("runs once even if false");
} while (false);

// foreach — iterating collections
string[] names = { "Alice", "Bob", "Carol" };
foreach (string name in names)
    Console.WriteLine(name);

// break and continue
for (int i = 0; i < 10; i++)
{
    if (i == 5) break;      // exits the loop
    if (i % 2 == 0) continue;  // skips even numbers
    Console.WriteLine(i);   // prints 1 3
}

Methods

C#
// Basic method
static int Add(int a, int b)
{
    return a + b;
}

// Expression-bodied method (same as above, shorter)
static int Multiply(int a, int b) => a * b;

// Default parameters
static void Greet(string name, string greeting = "Hello")
    => Console.WriteLine($"{greeting}, {name}!");

Greet("Alice");           // Hello, Alice!
Greet("Bob", "Hi");       // Hi, Bob!

// Named arguments — order doesn't matter
Greet(greeting: "Hey", name: "Carol");

// Out parameters — return multiple values
static bool TryParse(string s, out int result)
{
    result = 0;
    return int.TryParse(s, out result);
}

if (TryParse("42", out int val))
    Console.WriteLine(val);   // 42

// Params — variable number of arguments
static int Sum(params int[] numbers)
    => numbers.Sum();

Console.WriteLine(Sum(1, 2, 3, 4));   // 10

Strings

C#
string first = "Hello";
string last  = "World";

// Concatenation
string joined = first + " " + last;

// String interpolation (preferred)
string msg = $"Say {first} to {last}!";

// Verbatim strings (raw paths, no escape needed)
string path = @"C:\Users\alice\documents";

// Raw string literals (C# 11+, no escaping at all)
string json = """
    {
      "name": "Alice"
    }
    """;

// Common string methods
string s = "  Hello World  ";
Console.WriteLine(s.Trim());           // "Hello World"
Console.WriteLine(s.ToLower());        // "  hello world  "
Console.WriteLine(s.Contains("World")); // true
Console.WriteLine(s.Replace("World", "C#")); // "  Hello C#  "
Console.WriteLine(s.Split(' '));       // array of tokens

// String comparison (always use ordinal or invariant, not ==)
bool equal = string.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase);

Arrays and Collections

C#
// Array — fixed size
int[] numbers = new int[3];        // [0, 0, 0]
int[] primes  = { 2, 3, 5, 7 };   // initializer syntax

Console.WriteLine(primes[0]);   // 2
Console.WriteLine(primes.Length);  // 4

// List<T> — dynamic size
var list = new List<string> { "a", "b", "c" };
list.Add("d");
list.Remove("b");
Console.WriteLine(list.Count);  // 3

// Dictionary<TKey, TValue>
var scores = new Dictionary<string, int>
{
    ["Alice"] = 95,
    ["Bob"]   = 82,
};
scores["Carol"] = 90;

if (scores.TryGetValue("Alice", out int score))
    Console.WriteLine(score);   // 95

Interview Answer

"C# is statically typed — every variable has a compile-time type, which eliminates a class of runtime bugs. The var keyword uses type inference but is still static. Nullable reference types (enabled via <Nullable>enable</Nullable>) make null-safety explicit: string? can be null, string cannot — the compiler warns at the assignment site. String interpolation ($"{value}") is preferred over concatenation. Switch expressions replace verbose switch statements for value-returning logic. For collections: prefer List<T> over arrays when size varies, and Dictionary<TKey, TValue> for key lookups. Always use string.Equals with a StringComparison enum rather than == when culture or case sensitivity matters."

Enjoyed this article?

Explore the Backend Systems learning path for more.

Found this helpful?

Share:𝕏

Leave a comment

Have a question, correction, or just found this helpful? Leave a note below.