C# and .NET Fundamentals for Beginners: Syntax, Types and OOP
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
| Piece | What it does |
|---|---|
| C# language | The syntax you write in .cs files |
| .NET SDK | The 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 |
| NuGet | The package manager for third-party libraries |
From source code to a running program
- The C# compiler turns your
.csfiles into Intermediate Language (IL), stored in an assembly (a.dllfile). - When the program runs, the Common Language Runtime (CLR) loads the assembly.
- The Just-In-Time (JIT) compiler translates IL into machine code for the current processor, method by method.
- The garbage collector (GC) frees memory that is no longer used, so you do not free it by hand.
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.
Check yourself
- What does the C# compiler produce from your source files?
- Which component translates IL into machine code when a .NET program runs?
- What is the role of the garbage collector in .NET?
- Which command builds and runs a .NET console project from the terminal?
- Modern .NET (5 and later) runs only on Windows.
- What are top-level statements in C#?
- What is NuGet?
- Which services does the CLR provide to managed code?
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
| Type | Holds | Example |
|---|---|---|
int | 32-bit whole number | int age = 30; |
long | 64-bit whole number | long big = 5_000_000_000; |
double | 64-bit floating point | double pi = 3.14159; |
decimal | Exact decimal, for money | decimal price = 9.99m; |
bool | true or false | bool ok = true; |
char | One character | char c = 'A'; |
string | Text | string 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
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 exceptionStrings
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 textNull 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
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
- What is the value of the C# expression 7 / 2 when both operands are int?
- Which C# type is the best choice for storing money amounts?
- A variable declared with var can later be assigned a value of a different type.
- What does (int)3.9 evaluate to in C#?
- What happens when int.Parse("abc") runs?
- What does the ?? operator do in C#?
- Calling ToUpper() on a string modifies the original string.
- Which line correctly uses string interpolation?
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;
}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
| Loop | Use it when |
|---|---|
for | You know the number of iterations or need the index |
foreach | You visit every item of a collection |
while | You repeat while a condition holds, possibly zero times |
do while | The 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 testbreak 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
- Which C# loop always executes its body at least once?
- What does the continue statement do inside a loop?
- How many times does this loop print? for (int i = 0; i < 3; i++) Console.WriteLine(i);
- In C#, if (5) { } compiles because non-zero numbers count as true.
- In the expression a != null && a.Length > 0, what happens when a is null?
- In a switch expression, what does the _ pattern mean?
- What is the value of label after: string label = 40 >= 50 ? "pass" : "fail";
- C# lets execution fall through silently from one non-empty case into the next.
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 argumentsvoid 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
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 = 5Arrays
int[] nums = { 4, 8, 15 };
int first = nums[0]; // indexes start at 0
int size = nums.Length; // 3
int[] empty = new int[5]; // five zerosnums[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.
foreach over that list: it throws InvalidOperationException. Loop over a copy, or use RemoveAll.Check yourself
- What does the return type void mean for a C# method?
- What is the index of the first element of a C# array?
- Which property gives the number of items in a List<T>?
- What happens when you read a missing key with the indexer of a Dictionary, as in ages["Bob"]?
- What is the difference between ref and out parameters?
- Without ref or out, a method that changes an int parameter also changes the caller's variable.
- What is method overloading?
- The size of a C# array can grow after it is created by calling Add.
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);private and expose them through properties and methods, so the object controls its own state.Access modifiers
| Modifier | Visible from |
|---|---|
public | Anywhere |
private | The same class only (the default for members) |
protected | The class and its derived classes |
internal | The 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()); // WoofThe 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.
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
- What is the default access modifier of a class member (field or method) in C#?
- How many base classes can a C# class inherit from directly?
- Which keyword must a base class method have so that a derived class can override it?
- You can create an instance of an abstract class with new.
- Animal a = new Dog(); a.Speak(); where Speak is virtual in Animal and overridden in Dog. Which version runs?
- What is a constructor?
- What does a static member belong to?
- Which statements about interfaces are true?
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
}catch wins, and catch (Exception) placed first would hide all the others (the compiler reports an error).Common exception types
| Exception | Typical cause |
|---|---|
NullReferenceException | Using a member of a null reference |
ArgumentException, ArgumentNullException | A method received an invalid argument |
InvalidOperationException | The object is in the wrong state for the call |
IndexOutOfRangeException | Array index outside its bounds |
FormatException | Text in the wrong format, e.g. int.Parse("abc") |
DivideByZeroException | Integer 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
}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 blockGood practice
- Catch only what you can handle. Let other exceptions travel up.
- Never leave a
catchblock empty: it hides bugs. - Do not use exceptions for ordinary situations. Prefer
int.TryParseto catchingFormatExceptionfor user input. - An unhandled exception stops the program.
Check yourself
- When does a finally block run in C#?
- Why is throw; preferred to throw ex; when rethrowing a caught exception?
- In what order should catch blocks be written?
- Which exception is thrown when you call a method on a null reference?
- What does a using statement guarantee?
- Which interface must a type implement to be used in a using statement?
- An empty catch block is good practice because it keeps the program running.
- For validating number input typed by a user, which approach is preferred?