Brainbotox · Lessons · Exams

C# and .NET Fundamentals for Beginners: Syntax, Types and OOP

by lazizanie · Programming · C# / .NET · English

Learn C# and .NET from zero: the runtime, variables and types, control flow, methods, collections, classes and exceptions, with a quiz after each chapter.

Study this lesson with its quizzes on Brainbotox →

What are .NET and C#?

C# is a modern, strongly typed, object-oriented programming language, and .NET is the free, open-source, cross-platform platform that compiles and runs it on Windows, Linux and macOS.

The pieces of the platform

PieceWhat it does
C# languageThe syntax you write in .cs files
.NET SDKThe compiler (Roslyn) and the dotnet command line tool, used to create, build, test and publish projects
Runtime (CLR)Runs your program: loads assemblies, compiles them to machine code, manages memory
Base Class Library (BCL)Ready-made types: strings, collections, files, networking, JSON
NuGetThe package manager for third-party libraries

From source code to a running program

  1. The C# compiler turns your .cs files into Intermediate Language (IL), stored in an assembly (a .dll file).
  2. When the program runs, the Common Language Runtime (CLR) loads the assembly.
  3. The Just-In-Time (JIT) compiler translates IL into machine code for the current processor, method by method.
  4. The garbage collector (GC) frees memory that is no longer used, so you do not free it by hand.
Managed code is code that runs under the control of the CLR, which provides memory management, type safety and exception handling.

Your first program

dotnet new console -n Hello
cd Hello
dotnet run

The file Program.cs contains a single line:

Console.WriteLine("Hello, World!");

This short form is called top-level statements. The compiler generates the classic entry point for you, which older code writes in full:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}

Projects, namespaces and using

A project is described by a .csproj file, which names the target framework (for example net8.0) and the NuGet packages used. Types are grouped in namespaces such as System.Collections.Generic, and a using directive lets you write List instead of the full name.

A new .NET version ships every November. Even-numbered versions (8, 10) are Long Term Support (LTS) releases, the usual choice for production.
.NET Framework (4.x) is the older, Windows-only platform. Modern .NET (5 and later, formerly .NET Core) is cross-platform. They are not the same thing.

Check yourself

  1. What does the C# compiler produce from your source files?
  2. Which component translates IL into machine code when a .NET program runs?
  3. What is the role of the garbage collector in .NET?
  4. Which command builds and runs a .NET console project from the terminal?
  5. Modern .NET (5 and later) runs only on Windows.
  6. What are top-level statements in C#?
  7. What is NuGet?
  8. Which services does the CLR provide to managed code?

Take the quiz on Brainbotox

C# variables, data types and operators

A variable is a named storage location with a fixed type. C# is statically typed: the type of every variable is known at compile time and cannot change.

The common built-in types

TypeHoldsExample
int32-bit whole numberint age = 30;
long64-bit whole numberlong big = 5_000_000_000;
double64-bit floating pointdouble pi = 3.14159;
decimalExact decimal, for moneydecimal price = 9.99m;
booltrue or falsebool ok = true;
charOne characterchar c = 'A';
stringTextstring name = "Ada";

var and const

var count = 10;        // the compiler infers int
var name = "Ada";      // the compiler infers string
const double Vat = 0.2; // value fixed at compile time
var does not mean dynamic typing. count is an int forever, so count = "ten"; does not compile.

Arithmetic and comparison operators

int a = 7 / 2;      // 3   (integer division drops the remainder)
int r = 7 % 2;      // 1   (remainder)
double d = 7 / 2.0; // 3.5
bool same = a == 3; // true
bool both = a > 1 && r == 1; // logical AND
Dividing two integers gives an integer. Make one side a double or decimal to keep the fraction.

Converting between types

long big = a;              // implicit: no data can be lost
int n = (int)3.9;          // explicit cast: 3 (truncates)
int p = int.Parse("42");   // throws FormatException on bad input
bool ok = int.TryParse("abc", out int q); // false, no exception

Strings

A string is immutable: methods such as ToUpper() return a new string and leave the original unchanged. Use string interpolation to build text:

string name = "Ada";
int age = 36;
string msg = $"{name} is {age} years old";
bool eq = name == "Ada"; // true: == compares the text

Null and nullable types

int? maybe = null;          // nullable value type
int value = maybe ?? 0;     // ?? gives a default when null
string? s = null;
int? len = s?.Length;       // ?. returns null instead of crashing
Use decimal for money. double cannot represent values such as 0.1 exactly, so 0.1 + 0.2 == 0.3 is false with doubles.

Check yourself

  1. What is the value of the C# expression 7 / 2 when both operands are int?
  2. Which C# type is the best choice for storing money amounts?
  3. A variable declared with var can later be assigned a value of a different type.
  4. What does (int)3.9 evaluate to in C#?
  5. What happens when int.Parse("abc") runs?
  6. What does the ?? operator do in C#?
  7. Calling ToUpper() on a string modifies the original string.
  8. Which line correctly uses string interpolation?

Take the quiz on Brainbotox

C# control flow: if, switch and loops

Control flow statements decide which code runs and how many times. C# has conditions (if, switch) and four loops (for, foreach, while, do while).

if, else if, else

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

The condition must be a bool. Unlike C or JavaScript, if (score) does not compile for a number.

The conditional (ternary) operator

string label = score >= 50 ? "pass" : "fail";

Short-circuit evaluation

&& stops at the first false operand and || stops at the first true one. This makes the following safe:

if (text != null && text.Length > 0) { ... }

switch

switch (day)
{
    case "Sat":
    case "Sun":
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Weekday");
        break;
}
A non-empty case must end with break, return or throw. C# does not allow silent fall-through from one case into the next.

A switch expression returns a value and is shorter:

string kind = day switch
{
    "Sat" or "Sun" => "Weekend",
    _ => "Weekday"   // _ is the default
};

Loops

LoopUse it when
forYou know the number of iterations or need the index
foreachYou visit every item of a collection
whileYou repeat while a condition holds, possibly zero times
do whileThe body must run at least once
for (int i = 0; i < 3; i++)
    Console.WriteLine(i);        // 0 1 2
string[] names = { "Ada", "Bob" };
foreach (string n in names)
    Console.WriteLine(n);
int k = 10;
while (k > 0) k -= 3;            // ends with k = -2
do { k++; } while (k < 0);       // body runs before the test

break and continue

break leaves the loop completely. continue skips the rest of the current iteration and goes to the next one.
for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0) continue; // skip even numbers
    if (i > 6) break;         // stop the loop
    Console.WriteLine(i);     // 1 3 5
}

Check yourself

  1. Which C# loop always executes its body at least once?
  2. What does the continue statement do inside a loop?
  3. How many times does this loop print? for (int i = 0; i < 3; i++) Console.WriteLine(i);
  4. In C#, if (5) { } compiles because non-zero numbers count as true.
  5. In the expression a != null && a.Length > 0, what happens when a is null?
  6. In a switch expression, what does the _ pattern mean?
  7. What is the value of label after: string label = 40 >= 50 ? "pass" : "fail";
  8. C# lets execution fall through silently from one non-empty case into the next.

Take the quiz on Brainbotox

C# methods, arrays, List and Dictionary

A method is a named block of code that takes parameters and may return a value, and collections such as arrays, List<T> and Dictionary<TKey, TValue> store groups of values.

Declaring and calling methods

static int Add(int a, int b)
{
    return a + b;
}
static void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine($"{greeting}, {name}");
}
int sum = Add(2, 3);            // 5
Greet("Ada");                   // optional parameter uses its default
Greet(greeting: "Hi", name: "Bob"); // named arguments

void means the method returns nothing. Two methods can share a name if their parameter lists differ: this is overloading. A one-line method can use an expression body: static int Square(int x) => x * x;

Passing parameters: by value, ref and out

By default arguments are passed by value: the method receives a copy. ref and out pass the variable itself, so the method can change the caller's variable.
static void Double(ref int x) { x *= 2; }
static bool TryHalf(int x, out int half)
{
    half = x / 2;       // an out parameter must be assigned
    return x % 2 == 0;
}
int n = 5;
Double(ref n);          // n is now 10
bool even = TryHalf(n, out int h); // h = 5

Arrays

int[] nums = { 4, 8, 15 };
int first = nums[0];        // indexes start at 0
int size = nums.Length;     // 3
int[] empty = new int[5];   // five zeros
An array has a fixed size. Reading nums[3] here throws IndexOutOfRangeException.

List<T>: a resizable list

var names = new List<string> { "Ada" };
names.Add("Bob");
names.Remove("Ada");
int count = names.Count;    // Count for lists, Length for arrays
bool has = names.Contains("Bob");

Dictionary<TKey, TValue>: key to value

var ages = new Dictionary<string, int>();
ages["Ada"] = 36;           // add or replace
if (ages.TryGetValue("Bob", out int age))
    Console.WriteLine(age);
else
    Console.WriteLine("unknown");

Keys are unique. Reading a missing key with ages["Bob"] throws KeyNotFoundException, so prefer TryGetValue or ContainsKey.

Do not add or remove items of a list inside a foreach over that list: it throws InvalidOperationException. Loop over a copy, or use RemoveAll.

Check yourself

  1. What does the return type void mean for a C# method?
  2. What is the index of the first element of a C# array?
  3. Which property gives the number of items in a List<T>?
  4. What happens when you read a missing key with the indexer of a Dictionary, as in ages["Bob"]?
  5. What is the difference between ref and out parameters?
  6. Without ref or out, a method that changes an int parameter also changes the caller's variable.
  7. What is method overloading?
  8. The size of a C# array can grow after it is created by calling Add.

Take the quiz on Brainbotox

C# classes and objects: OOP basics

A class is a blueprint that groups data and behaviour, and an object is one instance created from it with new. Object-oriented programming in C# rests on encapsulation, inheritance and polymorphism.

A class with properties, a constructor and a method

public class BankAccount
{
    private decimal _balance;            // field, hidden from outside
    public string Owner { get; }         // read-only auto-property
    public decimal Balance => _balance;  // computed, read-only
    public BankAccount(string owner)     // constructor
    {
        Owner = owner;
    }
    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentException("Amount must be positive");
        _balance += amount;
    }
}
var acc = new BankAccount("Ada");
acc.Deposit(100m);
Encapsulation: keep fields private and expose them through properties and methods, so the object controls its own state.

Access modifiers

ModifierVisible from
publicAnywhere
privateThe same class only (the default for members)
protectedThe class and its derived classes
internalThe same assembly (the default for top-level classes)

static members

A static member belongs to the class itself, not to an object: Math.Sqrt(9), Console.WriteLine(). A static method cannot use this or instance fields.

Inheritance and polymorphism

public class Animal
{
    public virtual string Speak() => "...";
}
public class Dog : Animal
{
    public override string Speak() => "Woof";
}
Animal a = new Dog();
Console.WriteLine(a.Speak());   // Woof

The call runs the Dog version even though the variable is typed Animal: this is polymorphism. A method must be marked virtual (or abstract) in the base class to be overridden. Use base.Speak() to call the parent version.

A C# class can inherit from only one base class, but it can implement many interfaces.

Abstract classes and interfaces

public abstract class Shape
{
    public abstract double Area();     // no body: derived classes must implement
}
public interface IPrintable
{
    void Print();
}
public class Circle : Shape, IPrintable
{
    public double Radius { get; set; }
    public override double Area() => Math.PI * Radius * Radius;
    public void Print() => Console.WriteLine(Area());
}

An abstract class cannot be instantiated and can share code and state with its children. An interface is a contract: a list of members a type promises to provide. A sealed class cannot be inherited from.

Check yourself

  1. What is the default access modifier of a class member (field or method) in C#?
  2. How many base classes can a C# class inherit from directly?
  3. Which keyword must a base class method have so that a derived class can override it?
  4. You can create an instance of an abstract class with new.
  5. Animal a = new Dog(); a.Speak(); where Speak is virtual in Animal and overridden in Dog. Which version runs?
  6. What is a constructor?
  7. What does a static member belong to?
  8. Which statements about interfaces are true?

Take the quiz on Brainbotox

C# exceptions and error handling: try, catch, finally

An exception is an object that signals an error and interrupts the normal flow of a program. You handle it with try, catch and finally, and raise one with throw.

try, catch, finally

try
{
    string text = File.ReadAllText("data.txt");
    int n = int.Parse(text);
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"Missing file: {ex.FileName}");
}
catch (FormatException)
{
    Console.WriteLine("The file does not contain a number");
}
finally
{
    Console.WriteLine("Done");   // runs whether or not an exception occurred
}
Put specific exception types before general ones. The first matching catch wins, and catch (Exception) placed first would hide all the others (the compiler reports an error).

Common exception types

ExceptionTypical cause
NullReferenceExceptionUsing a member of a null reference
ArgumentException, ArgumentNullExceptionA method received an invalid argument
InvalidOperationExceptionThe object is in the wrong state for the call
IndexOutOfRangeExceptionArray index outside its bounds
FormatExceptionText in the wrong format, e.g. int.Parse("abc")
DivideByZeroExceptionInteger division by zero

Throwing exceptions

public void SetAge(int age)
{
    if (age < 0)
        throw new ArgumentOutOfRangeException(nameof(age), "Age cannot be negative");
    _age = age;
}

Rethrowing

catch (Exception ex)
{
    Log(ex);
    throw;        // keeps the original stack trace
}
Write throw;, not throw ex;. The second form resets the stack trace, which hides where the error really happened.

Custom exceptions

public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message) { }
}

using: releasing resources

Files, network connections and database connections implement IDisposable. A using statement calls Dispose() automatically at the end of the scope, even if an exception is thrown:

using var reader = new StreamReader("data.txt");
string line = reader.ReadLine();
// reader is disposed here, at the end of the enclosing block

Good practice

  • Catch only what you can handle. Let other exceptions travel up.
  • Never leave a catch block empty: it hides bugs.
  • Do not use exceptions for ordinary situations. Prefer int.TryParse to catching FormatException for user input.
  • An unhandled exception stops the program.

Check yourself

  1. When does a finally block run in C#?
  2. Why is throw; preferred to throw ex; when rethrowing a caught exception?
  3. In what order should catch blocks be written?
  4. Which exception is thrown when you call a method on a null reference?
  5. What does a using statement guarantee?
  6. Which interface must a type implement to be used in a using statement?
  7. An empty catch block is good practice because it keeps the program running.
  8. For validating number input typed by a user, which approach is preferred?

Take the quiz on Brainbotox