Vividly / Languages / C#

C#

C# is a modern, type-safe language from Microsoft used for desktop apps, web services, games, and cloud applications on the .NET platform.

Read the lesson →

Why this matters

C# gives you a productive balance between structure and convenience. It compiles to an intermediate language that the .NET runtime executes, with garbage collection, strong typing, and a huge standard library. That combination makes it a favourite for line-of-business applications and game development with Unity.

Learning C# is worthwhile because it teaches ideas that appear across the .NET ecosystem and beyond. You will meet properties, delegates, events, and async methods everywhere. Once these click, moving between web APIs, desktop tools, and game code becomes mostly a matter of learning new libraries.

The runtime is a practical advantage too. Garbage collection handles memory, a just-in-time compiler turns intermediate code into native instructions, and a single toolchain covers projects of very different sizes. You can start with a small console program and grow it into a web service without changing languages.

The big picture

A C# program is built from types, most often classes. A class can hold fields, properties, methods, and events. The compiler turns your source into an assembly containing intermediate language, and the runtime compiles that to native code when needed. This is why .NET apps can be both portable and fast.

The language evolves quickly but stays coherent. Features such as nullability annotations, pattern matching, and expression-bodied members are layered on top of the same core ideas. Focus first on types and methods, then add the newer syntax where it makes your code clearer rather than merely shorter.

Another way to picture a C# program is as a graph of objects sending messages. A method call is one such message, an event is a broadcast that interested objects subscribe to, and a task represents work that may finish later. Learning to see these connections helps you decide whether a feature belongs in a method, a property, or an event.

Core ideas

Classes and objects

A class describes the shape of an object: the data it holds and the operations it supports. You instantiate it with new, and the constructor runs to establish a valid initial state. Fields store raw data, while properties expose it with controlled access.

C# encourages you to keep fields private and expose properties. A property looks like a field to callers but runs code behind the scenes, so you can add validation or change storage later without touching client code. That is encapsulation with almost no ceremony.

Classes and objectsexample
class Product {
  public string Name { get; }
  public Product(string name) => Name = name;
}
var p = new Product("Notebook");

Watch out. Using public fields for everything. Prefer properties so you can add logic later.

Types and var

C# is statically typed. Value types such as int, double, and bool hold data directly, while reference types such as string and classes hold references to objects. The var keyword lets the compiler infer a local variable's type, but the variable stays strongly typed.

Reference types can be null unless you enable nullable reference types, which is the modern default in new projects. The compiler then warns when you might dereference null. Taking those warnings seriously eliminates a whole category of runtime crashes.

Types and varexample
int count = 3;
double price = 9.99;
var name = "Ada";
string? maybe = null;

Watch out. Treating var as dynamic. It is inferred once at compile time and never changes type.

Control flow

C# uses if, else, switch, for, foreach, while, and do in forms familiar from other C-style languages. Conditions must be boolean, and braces define blocks. The foreach loop is the natural way to walk a collection because it works against the collection's enumerator.

Pattern matching extends switch far beyond constant values. You can match on types, properties, and ranges, and bind matched values to variables in one expression. Used well, it replaces long chains of conditionals with compact, readable branches.

Control flowexample
foreach (var item in items) {
  Console.WriteLine(item);
}
var label = count switch {
  0 => "none",
  1 => "one",
  _ => "many"
};

Watch out. Modifying a collection while enumerating it with foreach. Build a new list instead.

Collections and LINQ

The .NET library offers List for ordered items, Dictionary for key-value pairs, and HashSet for uniqueness. They are generic, so the compiler knows what they contain. Initialisers let you populate them compactly at creation time.

LINQ adds query operations over any enumerable source. Methods such as Where, Select, OrderBy, and ToList compose into readable pipelines that replace manual loops. Queries are lazy by default, so they do no work until you enumerate the result.

Collections and LINQexample
var adults = people
  .Where(p => p.Age >= 18)
  .OrderBy(p => p.Name)
  .ToList();

Watch out. Enumerating a lazy query repeatedly. Call ToList once if you need to reuse the results.

Exceptions

Errors are reported with exceptions. You catch them with try and catch, and use finally or a using declaration for cleanup. Catch specific exception types, add context when rethrowing, and let unexpected errors propagate so they are visible during development.

The using statement calls Dispose automatically, which matters for files, streams, and database connections. Because disposal happens even when an exception is thrown, it is the right tool for any resource that must be released.

Exceptionsexample
try {
  using var reader = new StreamReader(path);
  return reader.ReadToEnd();
} catch (FileNotFoundException e) {
  throw new InvalidOperationException("Missing config", e);
}

Watch out. Catching all exceptions with an empty block. Handle what you understand and rethrow the rest.

Namespaces and projects

Namespaces organise types and prevent name clashes. A using directive imports a namespace so you can refer to its types by short names. Modern C# supports file-scoped namespaces, which remove one level of indentation from an entire file.

A project groups source files and dependencies into an assembly. The SDK-style project file lists the target framework and packages. Understanding this boundary helps you decide whether code belongs in the same project, a shared library, or a separate service.

Namespaces and projectsexample
using System;
using System.Collections.Generic;

namespace MyApp;

class Program {
  static void Main() => Console.WriteLine("Hello");
}

Watch out. Naming a namespace the same as a common type, which creates confusing resolution errors.

Methods

A method is a named, reusable block of code that belongs to a type. It declares a return type, a name, and a parameter list, then provides a body. Methods keep programs organised by giving each small job a clear, testable boundary.

C# has unusually rich method features. Parameters can be passed by reference, lists can be optional or variable length, and short methods can be written as expressions. Delegates and lambdas let you treat methods as values, which powers events and LINQ throughout the ecosystem.

Syntax and returns

A method declaration includes an access modifier, an optional modifier such as static, a return type, a PascalCase name, and parameters in parentheses. Use void when there is no result. Every path through a value-returning method must return a compatible value.

Think of the signature as a promise to callers. It states what you must supply and what you will get back, and the compiler checks both ends. When a method grows too large, the signature is usually the clue: split it into smaller methods whose names describe each step, and the program becomes easier to test and reuse.

Syntax and returnsexample
public int Square(int n) {
  return n * n;
}
public void Log(string message) {
  Console.WriteLine(message);
}

ref, out, and in

Arguments are passed by value by default, so a method cannot reassign the caller's variable. The ref modifier passes by reference and requires the variable to be initialised. out is like ref but the called method must assign it; in passes by reference read-only to avoid copying large structs.

ref, out, and inexample
bool TryParse(string text, out int value) {
  return int.TryParse(text, out value);
}
int result;
TryParse("42", out result);

Optional and params

Optional parameters have default values, so callers may omit them. Put them after required parameters to keep calls unambiguous. The params keyword accepts a variable number of arguments as an array, which is handy for helpers that aggregate several values.

Optional and paramsexample
void Greet(string name, string greeting = "Hello") {
  Console.WriteLine($"{greeting}, {name}");
}
int Sum(params int[] nums) => nums.Sum();
Sum(1, 2, 3);

Expression-bodied members

When a method is a single expression, you can replace braces and return with a fat arrow. This keeps small members compact without changing their meaning. Use it for genuinely simple operations; anything with branching is clearer in a normal block body.

Expression-bodied membersexample
public string FullName => First + " " + Last;
public int Double(int n) => n * 2;

Overloads

Several methods may share a name when their parameter lists differ. The compiler chooses the best match from the arguments. Overloads should behave consistently, and you should avoid optional parameters that produce ambiguous calls alongside an overload.

Overloadsexample
string Format(int value) => value.ToString("D3");
string Format(double value) => value.ToString("F2");
Format(7);
Format(7.5);

Extension methods

An extension method adds behaviour to an existing type without changing it. It must be a static method in a static class, with the target type as its first parameter prefixed by this. Once the namespace is imported, the method appears as an instance member in your editor.

Extension methodsexample
static class StringExtensions {
  public static bool IsEmail(this string s) => s.Contains('@');
}
"ada@example.com".IsEmail();

Lambdas and delegates

A delegate is a type that represents a method signature, and a lambda is a compact way to write an anonymous method that fits one. Lambdas are everywhere in LINQ and event handlers. They can capture variables from the surrounding scope, which is powerful but means you should watch lifetimes.

Lambdas and delegatesexample
Func<int, int> twice = x => x * 2;
var even = numbers.Where(n => n % 2 == 0);
button.Click += (sender, e) => Console.WriteLine("clicked");

Local functions and async

A local function is declared inside another method and is visible only there. It is useful for a helper that belongs to one algorithm. An async method returns a Task and uses await to pause without blocking a thread, which keeps user interfaces responsive and servers scalable.

Local functions and asyncexample
async Task<string> LoadAsync(string url) {
  using var client = new HttpClient();
  return await client.GetStringAsync(url);
}

Function reference

These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.

method

User-defined method

A method is a named block of code in a class that carries out a task. Defining one lets you call the same logic from many places instead of repeating it.

SyntaxreturnType Name(parameters) { body }
ParametersreturnType — The type returned, or void.
Name — The method name, usually PascalCase.
parameters — Typed inputs the method accepts.
ReturnsA value of the declared type, or nothing when the return type is void.
methodexample
public class Greeter {
  public string Greet(string name) {
    return "Hello, " + name;
  }
}

What you can do with it. Package a repeatable task under one name. Break a big program into testable pieces. Expose behaviour while hiding how it works.

Choose it when. Choose a method whenever you need reusable logic, rather than copying the same statements into several places.

MistakeFix
Forgetting a return on a non-void method.Return a value of the declared type on every path.
Giving a method a name that hides what it does.Use a clear verb such as CalculateTotal.

expression-bodied method

User-defined method

An expression-bodied method is a short method written with => instead of a full block. It keeps one-line methods compact and easy to scan.

SyntaxreturnType Name(parameters) => expression;
Parametersparameters — The typed inputs.
expression — A single expression whose value is returned.
ReturnsThe value of the expression, or nothing for a void method.
expression-bodied methodexample
public int Square(int n) => n * n;
public string Label(string s) => "Item: " + s;

What you can do with it. Write tiny helper methods in one line. Express simple calculations cleanly. Keep property-like getters concise.

Choose it when. Choose an expression body for short, single-purpose methods, rather than a full block that adds noise.

MistakeFix
Trying to put several statements into an expression body.Use a normal block with braces when you need multiple statements.
Forgetting the semicolon after the expression.End expression-bodied members with a semicolon.

async method

User-defined method

An async method runs work without blocking the calling thread. It uses await to pause until a task finishes, which keeps apps responsive during I/O.

Syntaxasync Task<T> Name() { ... await ...; }
Parametersasync — Marks the method as asynchronous.
Task<T> — The return type wrapping the eventual result.
ReturnsA Task or Task<T> representing the ongoing operation.
async methodexample
public async Task<string> LoadAsync(string url) {
  using var client = new HttpClient();
  return await client.GetStringAsync(url);
}

What you can do with it. Fetch data from a web API without freezing the UI. Read or write files asynchronously. Run several independent I/O tasks together.

Choose it when. Choose an async method for I/O-bound work, rather than blocking the thread with synchronous calls.

MistakeFix
Marking a method async with no await inside.Either add an await or remove the async keyword.
Calling an async method without awaiting it.Await the returned Task so you handle results and errors.

extension method

User-defined method

An extension method adds a method to an existing type without changing that type's source. It is declared as a static method with a special this parameter.

Syntaxpublic static ReturnType Name(this Type value, ...)
Parametersthis Type — Marks it as an extension and names the target type.
value — The instance the method is called on.
ReturnsWhatever the static method declares.
extension methodexample
public static class StringExt {
  public static bool IsEmail(this string s) =>
    s.Contains("@");
}

bool ok = "a@b.com".IsEmail();

What you can do with it. Add helpers to types you cannot edit. Create fluent, readable chains. Share common string or collection utilities.

Choose it when. Choose an extension method to add convenience to an existing type, rather than wrapping it in a helper class everywhere.

MistakeFix
Putting the extension method in a non-static class.Declare it in a static class.
Forgetting the this keyword on the first parameter.Start the parameter list with this Type name.

lambda/delegate

User-defined method

A lambda is a small anonymous function you can pass around as a value. Delegates and lambdas make callbacks and LINQ queries concise.

Syntax(parameters) => expression
Parametersparameters — The lambda's inputs, types often inferred.
expression — The body whose result is returned.
ReturnsA delegate that can be invoked or passed to another method.
lambda/delegateexample
Func<int, int> doubleIt = x => x * 2;
Predicate<string> isLong = s => s.Length > 5;
int result = doubleIt(4);

What you can do with it. Pass a comparison or filter into LINQ. Define short callbacks for events. Store a small piece of behaviour in a variable.

Choose it when. Choose a lambda for small, local behaviour passed as an argument, rather than writing a full named method.

MistakeFix
Expecting the lambda to run when it is defined.It runs only when the delegate is invoked or passed to a method that calls it.
Using a statement body without braces when you need several lines.Wrap multiple statements in braces.

Console.WriteLine

Standard library function

Console.WriteLine prints text to the console and adds a newline. It is the simplest way to see values while you are learning or debugging.

SyntaxConsole.WriteLine(value)
Parametersvalue — The value to print, often with string interpolation.
ReturnsNothing; it writes a line to standard output.
Console.WriteLineexample
string name = "Ada";
Console.WriteLine("Hello, " + name);
Console.WriteLine($"Score: {10 + 5}");

What you can do with it. Show results while learning. Print progress messages in a command-line tool. Inspect variable values during debugging.

Choose it when. Choose Console.WriteLine for quick text output in console apps, rather than building a full logging framework.

MistakeFix
Forgetting that it always appends a newline.Use Console.Write when you want to stay on the same line.
Passing an object and expecting a detailed dump.Format the fields you want, or override ToString.

int.Parse

Standard library function

int.Parse converts a string of digits into an int. You need it when text from input or a file must become a number for calculations.

Syntaxint.Parse(string)
Parametersstring — Text containing a whole number.
ReturnsAn int parsed from the text.
int.Parseexample
string input = "42";
int value = int.Parse(input);
Console.WriteLine(value + 1);

What you can do with it. Convert user input into a number. Read numeric values from configuration. Turn split text into integers.

Choose it when. Choose int.Parse when you are sure the text is a valid integer, otherwise prefer TryParse.

MistakeFix
Passing text that is not a valid number.Use int.TryParse to handle failure without an exception.
Ignoring leading or trailing spaces.Trim the string before parsing.

List<T>.Add

Standard library function

Add appends an item to a List<T>, growing it automatically. It is the common way to build a collection when you do not know the final size.

Syntaxlist.Add(item)
Parametersitem — An element of type T to append.
ReturnsNothing; the list is modified in place.
List<T>.Addexample
var names = new List<string>();
names.Add("Ada");
names.Add("Grace");
Console.WriteLine(names.Count);

What you can do with it. Gather results while reading data. Collect user selections. Build a list before binding it to a UI.

Choose it when. Choose List<T>.Add for a growable collection, rather than a fixed-size array.

MistakeFix
Adding an item of the wrong type.Match the list's generic type, such as List<string>.
Expecting Add to return the new count.It returns void; read list.Count afterward.

Dictionary.TryGetValue

Standard library function

TryGetValue looks up a key and reports whether it existed, avoiding an exception. It is the safe way to read from a dictionary when a key may be missing.

Syntaxdictionary.TryGetValue(key, out value)
Parameterskey — The key to look for.
value — An out variable that receives the value if found.
ReturnsA bool that is true when the key was found.
Dictionary.TryGetValueexample
var ages = new Dictionary<string, int>();
ages["Ada"] = 36;
if (ages.TryGetValue("Ada", out int age)) {
  Console.WriteLine(age);
}

What you can do with it. Look up optional configuration safely. Avoid exceptions during missing-key lookups. Fetch a value and use it in one step.

Choose it when. Choose TryGetValue when missing keys are normal, rather than catching exceptions from the indexer.

MistakeFix
Using the indexer for keys that may be missing.Use TryGetValue to avoid a KeyNotFoundException.
Ignoring the returned bool.Check it before using the out value.

Math.Max

Standard library function

Math.Max returns the larger of two numbers. It is a compact helper that replaces a simple if comparison.

SyntaxMath.Max(a, b)
Parametersa — The first number.
b — The second number.
ReturnsThe greater of a and b.
Math.Maxexample
int top = Math.Max(10, 20);
double width = Math.Max(0.5, ratio);

What you can do with it. Clamp a value to a minimum. Find the larger of two measurements. Compute the bigger dimension for layout.

Choose it when. Choose Math.Max for a quick two-value comparison, rather than an if/else block.

MistakeFix
Passing arguments of different numeric types by mistake.Use a common type so overload resolution is clear.
Looking for a three-argument version.Nest calls, like Math.Max(a, Math.Max(b, c)).

File.ReadAllText

Standard library function

File.ReadAllText reads an entire text file into a single string and closes the file for you. It is convenient for small files you need all at once.

SyntaxFile.ReadAllText(path)
Parameterspath — The file path, relative to the working directory or absolute.
ReturnsA string containing the full contents of the file.
File.ReadAllTextexample
string text = File.ReadAllText("notes.txt");
Console.WriteLine(text.Length);

What you can do with it. Load a configuration or template file. Read a small data file into memory. Display the contents of a text document.

Choose it when. Choose File.ReadAllText for small files you need in full, rather than streaming huge files.

MistakeFix
Using it on very large files.Stream the file line by line with StreamReader instead.
Not handling a missing file.Catch FileNotFoundException or check File.Exists first.

string.IsNullOrEmpty

Standard library function

string.IsNullOrEmpty checks whether a string is null or has zero length. It combines two common checks into one safe call.

Syntaxstring.IsNullOrEmpty(value)
Parametersvalue — The string to test, which may be null.
ReturnsTrue when the string is null or empty, otherwise false.
string.IsNullOrEmptyexample
string input = GetInput();
if (string.IsNullOrEmpty(input)) {
  Console.WriteLine("Missing");
}

What you can do with it. Validate required fields before processing. Guard code that expects a real string. Skip optional values that were not supplied.

Choose it when. Choose string.IsNullOrEmpty for a simple presence check, rather than writing two separate conditions.

MistakeFix
Checking only for null and missing empty strings.Use IsNullOrEmpty so both cases are covered.
Wanting to treat whitespace as empty.Add string.IsNullOrWhiteSpace for that case.

DateTime.Now

Standard library function

DateTime.Now gives you the current local date and time as a DateTime value. It is a property, not a method, so you use it without parentheses.

SyntaxDateTime.Now
ReturnsA DateTime representing the current local date and time.
DateTime.Nowexample
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd"));
Console.WriteLine(now.Hour);

What you can do with it. Stamp records with the current time. Show a live clock in an app. Measure elapsed time with a second DateTime.

Choose it when. Choose DateTime.Now for local time display, rather than UTC when correctness across time zones matters.

MistakeFix
Adding parentheses, as in DateTime.Now().It is a property; write DateTime.Now.
Using local time when you need UTC.Use DateTime.UtcNow for timestamps shared across systems.

Enumerable.Where

Standard library function

Where filters a sequence to the items that match a condition. Combined with other LINQ operators, it lets you query collections in a readable way.

Syntaxsource.Where(predicate)
Parameterspredicate — A lambda returning true for items to keep.
ReturnsAn IEnumerable<T> of the matching items, evaluated lazily.
Enumerable.Whereexample
var adults = people.Where(p => p.Age >= 18);
foreach (var person in adults) {
  Console.WriteLine(person.Name);
}

What you can do with it. Select records that match a rule. Chain filtering with ordering and projection. Replace manual loops with clear queries.

Choose it when. Choose Enumerable.Where for readable filtering over sequences, rather than writing a loop with a nested if.

MistakeFix
Expecting Where to build a new list immediately.It is lazy; call ToList to materialise the results.
Thinking Where changes the source collection.It leaves the original untouched and yields matching items.

Common mistakes here

MistakeFix
Using out where ref would preserve an existing value.Use ref if the caller's starting value matters; out discards it.
Placing optional parameters before required ones.Put all optional parameters at the end.
Writing async void methods except for event handlers.Return Task so callers can await and observe failures.
Forgetting await inside an async method.Await the task, or return the task directly instead of marking async.
Making an extension method in a non-static class.Extension methods must live in a static class and be static.

The example, line by line

This program uses a themed greeter with an optional parameter and an expression-bodied method.

CodeWhat it does
1using System;Imports the System namespace for Console and core types.
2class GreeterDeclares the Greeter class that groups the program's methods.
3{Opens the class body.
4 static void Main()Declares the entry point called when the program starts.
5 {Opens the Main method body.
6 var message = Build("Ada", 3);Calls Build with two arguments and stores the returned string.
7 Console.WriteLine(message);Writes the result to the console.
8 }Closes the Main method.
9 static string Build(string name, int repeats)Declares a static method returning a string.
10 => string.Join(" ", System.Linq.Enumerable.Repeat("Hi " + name, repeats));Uses an expression body to join repeated greetings into one string.
11}Closes the class body.
Full examplecomplete
using System;
class Greeter
{
    static void Main()
    {
        var message = Build("Ada", 3);
        Console.WriteLine(message);
    }
    static string Build(string name, int repeats)
        => string.Join(" ", System.Linq.Enumerable.Repeat("Hi " + name, repeats));
}

Worked variations

A Try pattern

The Try pattern is a C# convention: a method returns a bool and produces its result through an out parameter. It avoids exceptions for expected failures such as invalid user input.

A Try patternvariation
bool TryGetAge(string text, out int age) {
  if (int.TryParse(text, out age) && age >= 0) return true;
  age = 0;
  return false;
}

A query pipeline

Lambdas shine in LINQ. Each operator takes a small function describing one step, and the pipeline reads like a sentence describing what you want rather than how to loop for it.

A query pipelinevariation
var names = orders
  .Where(o => o.Total > 100)
  .Select(o => o.Customer.Name)
  .Distinct()
  .ToList();

An async downloader

Async methods let an application stay responsive while waiting for slow I/O. Await suspends the method without tying up a thread, and the rest of the program keeps running.

An async downloadervariation
async Task<int> DownloadLengthAsync(string url) {
  using var client = new HttpClient();
  var text = await client.GetStringAsync(url);
  return text.Length;
}

Common mistakes

MistakeFix
Returning null from a method declared to return a non-nullable reference type.Return a meaningful value or change the return type to be nullable.
Using params for a list you already have.Pass the list directly with the spread-free overload instead.
Calling an async method without awaiting it.Await the returned Task unless you deliberately want fire-and-forget.
Overusing extension methods for domain logic.Keep them small and put core behaviour on the type itself.
Capturing a loop variable in a lambda unexpectedly.Use a local copy inside the loop or rely on modern foreach semantics.

Practice

  1. Write a method with an optional parameter and call it both with and without that argument.
  2. Use an out parameter in a Try-style method that parses a number safely.
  3. Create an extension method that formats a decimal as currency and call it on a value.
  4. Write an async method that fetches a string and returns its length, then await it.
Atmospheric photograph for this chapter Curved glass and steel lattice roof Stepped white modern building corner
Systems and connections. Follow one thread through to the end.

Where next