C# (pronounced “C sharp”) is a modern, strongly typed language from Microsoft. It runs on .NET, which works on Windows, Linux and macOS, and it is used for almost everything: web sites and APIs with ASP.NET Core, desktop and mobile apps, cloud services on Azure, games with Unity, and automation. It is also the natural language to use with SQL Server, which makes it a popular choice for the business systems that many administrators support. C# is an excellent first language because the compiler catches many mistakes before the program even runs, and it is a rewarding one because the same skills carry you from small scripts to large systems.
This tutorial starts from zero and builds up to classes, interfaces, generics, LINQ, async code, files and JSON, a small web API and a complete project. Every example was compiled and run with the .NET SDK before this page was published, and the results in the comments are the real results. If you are coming from our Python tutorial, the last section compares the two languages side by side.
How the code is shown. Modern C# lets you write simple programs as top-level statements: just lines of code in
Program.cs, with no ceremony. Examples are therefore short snippets that you paste intoProgram.cs. Type declarations (classes, records and so on) are shown in their own blocks: in a real file, put them below the statements, or in separate files.
Contents
- 1. Installing .NET and your first program
- 2. Variables, types and strings
- 3. Decisions and loops
- 4. Arrays, lists, dictionaries and sets
- 5. Methods
- 6. Classes, inheritance and interfaces
- 7. Records, structs, enums and tuples
- 8. Generics and extension methods
- 9. Null safety
- 10. Pattern matching
- 11. Exceptions and cleanup
- 12. LINQ: querying collections
- 13. Delegates, lambdas and events
- 14. Async and await
- 15. Files, JSON and dates
- 16. Projects, NuGet, dependency injection and tests
- 17. A web API with ASP.NET Core
- 18. Databases
- 19. A complete small project
- 20. Good habits, mistakes, and C# compared with Python
1. Installing .NET and your first program
You need the .NET SDK. It contains the compiler, the runtime and the dotnet command. Use the current long-term-support release (.NET 8 or newer); everything here works on 8, 9 and 10.
winget install Microsoft.DotNet.SDK.8 # Windows
sudo dnf install dotnet-sdk-8.0 # Red Hat, Rocky, AlmaLinux, Fedora
sudo apt install dotnet-sdk-8.0 # Ubuntu (22.04 and later)
brew install --cask dotnet-sdk # macOS
dotnet --version # check the installation
Your editor: Visual Studio (Windows, full-featured, free Community edition), Visual Studio Code with the C# Dev Kit extension (any system), or JetBrains Rider. Then create and run a project:
dotnet new console -o Hello # a new console application in the folder Hello
cd Hello
dotnet run # compile and run it
dotnet build # compile only
dotnet publish -c Release # produce the files you deploy
The template creates Program.cs (your code) and Hello.csproj (the project file):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <!-- common "using" lines are added for you -->
<Nullable>enable</Nullable> <!-- the compiler helps you avoid null errors -->
</PropertyGroup>
</Project>
How it works: the compiler turns your C# into an intermediate language (IL) stored in a .dll; when you run it, the .NET runtime compiles that to machine code just in time (JIT) and manages memory for you with a garbage collector. You never free memory by hand.
Hello, world
Console.WriteLine("Hello, world!"); // Hello, world!
That single line is a complete program. Console.WriteLine prints text followed by a new line; Console.Write prints without one. Statements end with a semicolon, blocks use curly braces, and the language is case-sensitive. Comments start with //, or /* ... */ for several lines.
Console.Write("Your name? ");
string? name = Console.ReadLine(); // returns null when there is no more input
Console.WriteLine($"Hello, {name ?? "stranger"}!"); // Hello, Sara! (the test run typed "Sara")
2. Variables, types and strings
C# is statically typed: every variable has a type that is fixed at compile time. That is what lets the compiler find mistakes early and lets your editor suggest code accurately.
| Type | Holds | Example |
|---|---|---|
int, long |
Whole numbers (32 and 64 bit) | 42, 9_000_000_000L |
double, float |
Fractional numbers (approximate) | 3.14, 2.5f |
decimal |
Exact decimal numbers: use for money | 19.99m |
bool |
true or false | true |
char |
One character | 'A' |
string |
Text | "Sara" |
DateTime, TimeSpan |
A moment, a duration | see section 15 |
object |
Anything (the base of all types) |
int age = 31;
long big = 9_000_000_000L; // underscores make long numbers readable
double height = 1.68;
decimal price = 19.99m; // the m suffix makes a decimal literal
bool isAdmin = true;
char grade = 'A';
string name = "Sara";
var count = 10; // var: the compiler infers the type (int). It is still strongly typed
const double Pi = 3.14159; // a constant cannot change
Console.WriteLine($"{name} is {age}, {height} m tall; price {price:F2}, pi {Pi}");
// Sara is 31, 1.68 m tall; price 19.99, pi 3.14159
Console.WriteLine($"{count.GetType()} {big.GetType()} {price.GetType().Name}"); // System.Int32 System.Int64 Decimal
Numbers behave in a few surprising ways. Integer division discards the fraction; a double cannot store 0.1 exactly; an int that gets too big silently wraps around unless you ask the compiler to check:
Console.WriteLine(7 / 2); // 3 integer division
Console.WriteLine(7 / 2.0); // 3.5 one side is a double
Console.WriteLine(7 % 2); // 1 remainder
Console.WriteLine(Math.Pow(2, 10)); // 1024
Console.WriteLine(Math.Round(2.5)); // 2 .NET rounds halves to the nearest EVEN number
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero)); // 3 (what most people expect)
Console.WriteLine(0.1 + 0.2); // 0.30000000000000004
Console.WriteLine(0.1m + 0.2m); // 0.3 decimal is exact for decimal fractions
int max = int.MaxValue;
Console.WriteLine(max + 1); // -2147483648 it wrapped around!
try { Console.WriteLine(checked(max + 1)); }
catch (OverflowException) { Console.WriteLine("overflow detected"); } // overflow detected
Converting between types
using System.Globalization;
Console.WriteLine((int)3.9); // 3 a cast cuts the decimals
Console.WriteLine(int.Parse("42") + 1); // 43
Console.WriteLine(Convert.ToInt32("7") * 2); // 14
Console.WriteLine(double.Parse("3.5", CultureInfo.InvariantCulture)); // 3.5
if (int.TryParse("abc", out int number)) // TryParse never throws: it returns true or false
Console.WriteLine(number);
else
Console.WriteLine("not a number"); // not a number
Console.WriteLine(42.ToString("D5") + " " + 3.14159.ToString("F2") + " " + 1234567.891.ToString("N1", CultureInfo.InvariantCulture)); // 00042 3.14 1,234,567.9
Always prefer TryParse for text typed by a user. Number formats depend on the culture (decimal comma or point): pass CultureInfo.InvariantCulture when you parse or write data that machines will read.
Strings
Strings are immutable: methods return a new string and never change the original.
string s = "C# is fun";
Console.WriteLine(s.Length + " " + s[0] + " " + s[^1]); // 9 C n (^1 means "from the end")
Console.WriteLine(s.Substring(6) + " | " + s[..2] + " | " + s[3..5]); // fun | C# | is
Console.WriteLine(s.ToUpper() + " " + s.Replace("fun", "great")); // C# IS FUN C# is great
Console.WriteLine(s.Contains("is") + " " + s.StartsWith("C#") + " " + s.IndexOf("fun")); // True True 6
Console.WriteLine(" padded ".Trim() + "|" + string.Join("-", "a,b,c".Split(','))); // padded|a-b-c
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Console.WriteLine(string.Equals("ABC", "abc", StringComparison.OrdinalIgnoreCase)); // True
string path = @"C:\Users\Sara\notes.txt"; // verbatim string: backslashes are literal
string json = """
{ "name": "Sara", "age": 31 }
"""; // raw string literal: quotes need no escaping
Console.WriteLine(path + " " + json);
var sb = new System.Text.StringBuilder(); // building text in a loop? use a StringBuilder
for (int i = 1; i <= 3; i++) sb.Append(i).Append(',');
Console.WriteLine(sb.ToString().TrimEnd(',')); // 1,2,3
Interpolation with $"..." is the standard way to build text: $"{price:F2}" formats a number inside it, and $"{name,-10}|{age,5}" pads columns. String concatenation with + in a big loop is slow, because each step creates a new string: use StringBuilder.
3. Decisions and loops
int temperature = 22;
if (temperature > 30)
Console.WriteLine("hot");
else if (temperature > 18)
Console.WriteLine("pleasant"); // pleasant
else
Console.WriteLine("cold");
string label = temperature > 20 ? "warm" : "cool"; // the conditional ("ternary") operator
Console.WriteLine(label); // warm
Console.WriteLine(temperature > 20 && temperature < 25); // True (&& and, || or, ! not)
Use == to compare values (for strings it compares the text). C# stops evaluating && and || as soon as the result is known, so if (user != null && user.IsActive) is safe.
switch: statement and expression
DayOfWeek day = DayOfWeek.Saturday;
switch (day) // the classic statement
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("weekend"); // weekend
break;
default:
Console.WriteLine("weekday");
break;
}
string kind = day switch // the switch EXPRESSION: shorter, and it returns a value
{
DayOfWeek.Saturday or DayOfWeek.Sunday => "weekend",
_ => "weekday" // _ means "anything else"
};
Console.WriteLine(kind); // weekend
int score = 73;
string grade = score switch
{
>= 90 => "A",
>= 70 => "B",
>= 50 => "C",
_ => "F"
};
Console.WriteLine(grade); // B
Loops
for (int i = 0; i < 3; i++)
Console.Write($"round {i}; "); // round 0; round 1; round 2;
Console.WriteLine();
foreach (char c in "abc") // foreach works on anything you can enumerate
Console.Write(c + " "); // a b c
Console.WriteLine();
int n = 0;
while (n < 3) n++; // checks first
do { n--; } while (n > 0); // runs at least once, checks after
Console.WriteLine(n); // 0
foreach (int number in Enumerable.Range(2, 18)) // numbers 2 to 19
{
if (number % 2 == 0) continue; // skip to the next one
if (number > 7) break; // leave the loop
Console.Write(number + " "); // 3 5 7
}
Console.WriteLine();
4. Arrays, lists, dictionaries and sets
| Type | Use it for | Notes |
|---|---|---|
T[] array |
A fixed number of items | Fastest, size cannot change |
List<T> |
The everyday growable list | Add, insert, remove, index |
Dictionary<K,V> |
Look up values by key | Near-instant lookups |
HashSet<T> |
Unique items, fast “is it in?” | No duplicates, no order |
Queue<T>, Stack<T> |
First-in-first-out, last-in-first-out | Enqueue/Dequeue, Push/Pop |
int[] numbers = { 5, 2, 9, 1 }; // an array
Array.Sort(numbers);
Console.WriteLine(string.Join(",", numbers) + " " + numbers.Length + " " + numbers[^1]); // 1,2,5,9 4 9
List<string> fruits = new() { "apple", "banana", "cherry" };
fruits.Add("date");
fruits.Insert(1, "avocado");
fruits.Remove("banana");
Console.WriteLine(string.Join(", ", fruits) + " | " + fruits.Count + " | " + fruits.IndexOf("cherry"));
// apple, avocado, cherry, date | 4 | 2
List<int> evens = [2, 4, 6]; // collection expressions (C# 12)
int[] more = [8, 10];
List<int> all = [..evens, ..more]; // .. spreads another collection in
Console.WriteLine(string.Join(" ", all) + " | " + string.Join(" ", all[1..3])); // 2 4 6 8 10 | 4 6
var ages = new Dictionary<string, int> { ["Ann"] = 31, ["Bob"] = 25 };
ages["Cy"] = 40; // add or replace
Console.WriteLine(ages["Ann"] + " " + ages.ContainsKey("Dan")); // 31 False
if (ages.TryGetValue("Dan", out int danAge)) // the safe way to look up: no exception if missing
Console.WriteLine(danAge);
else
Console.WriteLine("Dan not found"); // Dan not found
foreach (var (name, age) in ages.OrderBy(p => p.Value))
Console.Write($"{name}={age} "); // Bob=25 Ann=31 Cy=40
Console.WriteLine();
var wordCounts = new Dictionary<string, int>();
foreach (string w in "the cat and the dog and the bird".Split(' '))
wordCounts[w] = wordCounts.GetValueOrDefault(w) + 1; // the counting pattern
Console.WriteLine(string.Join(", ", wordCounts.Select(p => $"{p.Key}:{p.Value}"))); // the:3, cat:1, and:2, dog:1, bird:1
var set = new HashSet<int> { 1, 2, 3, 3, 3 };
Console.WriteLine(set.Count + " " + set.Contains(2) + " " + set.Add(2)); // 3 True False (Add returns false for a duplicate)
var queue = new Queue<string>(); queue.Enqueue("a"); queue.Enqueue("b");
var stack = new Stack<string>(); stack.Push("a"); stack.Push("b");
Console.WriteLine(queue.Dequeue() + " " + stack.Pop()); // a b
list[i] on a missing index throws ArgumentOutOfRangeException, and dictionary[key] on a missing key throws KeyNotFoundException. Use TryGetValue when a key may be missing. Searching a List with Contains reads every item; if you do it often, use a HashSet (see our algorithms tutorial for why).
5. Methods
A method is a named block of code with parameters and a return type (void if it returns nothing). In top-level code you can declare local functions right where you need them.
int Add(int a, int b) => a + b; // an expression-bodied method
string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!"; // optional parameter
int Sum(params int[] values) => values.Sum(); // params: any number of arguments
double Average(IEnumerable<double> values) { return values.Average(); }
Console.WriteLine(Add(2, 3)); // 5
Console.WriteLine(Greet("Sara")); // Hello, Sara!
Console.WriteLine(Greet(greeting: "Salam", name: "Omar")); // Salam, Omar! (named arguments, any order)
Console.WriteLine(Sum(1, 2, 3, 4) + " " + Average(new[] { 1.0, 2, 3, 4 })); // 10 2.5
bool TryDivide(int a, int b, out int result) // out: the method hands back an extra value
{
result = 0;
if (b == 0) return false;
result = a / b;
return true;
}
if (TryDivide(10, 2, out int q)) Console.WriteLine(q); // 5
void Double(ref int x) { x *= 2; } // ref: the method changes YOUR variable
int value = 21; Double(ref value);
Console.WriteLine(value); // 42
(int Min, int Max) MinMax(int[] items) => (items.Min(), items.Max()); // return several values with a tuple
var (lo, hi) = MinMax(new[] { 4, 8, 1 });
Console.WriteLine(lo + " " + hi); // 1 8
long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1); // recursion
Console.WriteLine(Factorial(10)); // 3628800
Value vs reference: numbers, booleans and structs are copied when you pass them; classes are passed as references, so a method can change the object’s contents. ref and out are the exception for value types. Several methods may have the same name if their parameters differ (overloading).
6. Classes, inheritance and interfaces
A class is a blueprint that combines data (fields and properties) with behaviour (methods). An object is one instance made with new. Properties are the C# way to expose data: they look like fields but can contain logic.
public class Person
{
public static int Created { get; private set; } // shared by every Person; only this class can change it
public string Name { get; set; } // an auto-property
public DateOnly Born { get; init; } // init: can be set when creating the object, never later
private int _visits; // a private field: hidden from outside
public Person(string name, DateOnly born) // the constructor
{
Name = name;
Born = born;
Created++;
}
public int Age(DateOnly today) =>
today.Year - Born.Year - (today < Born.AddYears(today.Year - Born.Year) ? 1 : 0);
public void Visit() => _visits++;
public int Visits => _visits; // a read-only property
public override string ToString() => $"{Name} (born {Born:yyyy-MM-dd})";
}
var sara = new Person("Sara", new DateOnly(1995, 3, 14)) { Name = "Sara A." }; // object initializer
sara.Visit(); sara.Visit();
Console.WriteLine(sara + " | age " + sara.Age(new DateOnly(2026, 10, 30)) + " | visits " + sara.Visits);
// Sara A. (born 1995-03-14) | age 31 | visits 2
Console.WriteLine(Person.Created > 0); // True: static members belong to the class, not an object
Access modifiers control who can see a member: public (everyone), private (this class only, the default for members), protected (this class and subclasses), internal (this project). Keep data private and expose only what others need: this is encapsulation, and it lets you change the inside of a class without breaking its users.
C# 12 adds primary constructors, a shorter way to declare a constructor when a class just stores what it receives:
public class Counter(string name, int start = 0)
{
private int _value = start;
public string Name { get; } = name;
public int Next() => ++_value;
}
var c = new Counter("hits", 10);
Console.WriteLine(c.Name + " " + c.Next() + " " + c.Next()); // hits 11 12
Inheritance and polymorphism
A class can inherit from one other class and gain its members. A virtual method can be replaced with override in a subclass, and an abstract class cannot be created itself but forces subclasses to fill in the gaps.
public abstract class Shape
{
public abstract double Area(); // no body: every shape must implement it
public virtual string Describe() => $"{GetType().Name} with area {Area():F2}";
}
public class Circle(double radius) : Shape
{
public override double Area() => Math.PI * radius * radius;
}
public class Rectangle(double width, double height) : Shape
{
public override double Area() => width * height;
public override string Describe() => "A rectangle! " + base.Describe(); // base calls the parent's version
}
List<Shape> shapes = [new Circle(2), new Rectangle(3, 4)];
foreach (Shape shape in shapes)
Console.WriteLine(shape.Describe()); // each call runs the right override: polymorphism
// Circle with area 12.57
// A rectangle! Rectangle with area 12.00
Console.WriteLine(shapes.Sum(s => s.Area()).ToString("F1")); // 24.6
Interfaces
An interface is a contract: a list of members that a class promises to provide. A class can inherit only one class, but implement many interfaces. Interfaces are the key to flexible, testable code, because your code can depend on “something that can send mail” instead of one specific mailer.
public interface INotifier
{
void Send(string to, string message);
}
public class ConsoleNotifier : INotifier
{
public void Send(string to, string message) => Console.WriteLine($"[console] to {to}: {message}");
}
public class FakeNotifier : INotifier // handy in tests: records instead of sending
{
public List<string> Sent { get; } = [];
public void Send(string to, string message) => Sent.Add($"{to}:{message}");
}
public class OrderService(INotifier notifier) // depends on the interface, not on a class
{
public void Place(string customer) => notifier.Send(customer, "Your order is confirmed");
}
new OrderService(new ConsoleNotifier()).Place("sara@example.com"); // [console] to sara@example.com: Your order is confirmed
var fake = new FakeNotifier();
new OrderService(fake).Place("omar@example.com");
Console.WriteLine(fake.Sent.Count + " " + fake.Sent[0]); // 1 omar@example.com:Your order is confirmed
Prefer composition (“has a”) over deep inheritance (“is a”), and keep inheritance trees shallow. Mark a class sealed if it should not be inherited.
7. Records, structs, enums and tuples
Records: data with value equality
A record is a class (or struct) designed to hold data. The compiler writes equality, ToString and copy support for you. Two records with the same values are equal, which is what you want for data.
public record Employee(string Name, string Department, decimal Salary);
public record Point(int X, int Y);
var a = new Point(3, 4);
var b = new Point(3, 4);
var moved = a with { X = 10 }; // a modified COPY: records are meant to be immutable
Console.WriteLine(a + " | " + (a == b) + " | " + moved + " | " + ReferenceEquals(a, b));
// Point { X = 3, Y = 4 } | True | Point { X = 10, Y = 4 } | False
var (x, y) = a; // deconstruction
Console.WriteLine(x + y); // 7
Structs, enums and tuples
public readonly struct Money(decimal amount, string currency) // a struct is a VALUE type: copied on assignment
{
public decimal Amount { get; } = amount;
public string Currency { get; } = currency;
public override string ToString() => $"{Amount:F2} {Currency}";
}
public enum Priority { Low = 1, Medium = 2, High = 3 }
[Flags]
public enum Permissions { None = 0, Read = 1, Write = 2, Delete = 4 }
Console.WriteLine(new Money(19.5m, "USD")); // 19.50 USD
Priority p = Priority.High;
Console.WriteLine($"{p} = {(int)p}, parsed: {Enum.Parse<Priority>("Low")}"); // High = 3, parsed: Low
var access = Permissions.Read | Permissions.Write; // combine flags with |
Console.WriteLine(access + " " + access.HasFlag(Permissions.Write) + " " + access.HasFlag(Permissions.Delete)); // Read, Write True False
var person = (Name: "Sara", Age: 31); // a tuple: a quick, unnamed-type group of values
Console.WriteLine($"{person.Name} {person.Age}"); // Sara 31
Use a class for things with identity and behaviour, a record for data, a struct only for small, immutable values (like a point or an amount), and an enum for a fixed set of named choices.
8. Generics and extension methods
Generics let you write code once for many types. You already used them: List<int> and List<string> are the same code with different type arguments, and the compiler keeps everything type-safe.
public class Box<T>
{
private readonly List<T> _items = [];
public void Add(T item) => _items.Add(item);
public T First() => _items[0];
public int Count => _items.Count;
}
public static class MathHelper
{
public static T Largest<T>(IEnumerable<T> items) where T : IComparable<T> // a constraint: T must be comparable
{
T best = items.First();
foreach (T item in items)
if (item.CompareTo(best) > 0) best = item;
return best;
}
}
public static class StringExtensions
{
public static bool IsPalindrome(this string text) // "this" makes it an extension method
{
string clean = new string(text.Where(char.IsLetterOrDigit).ToArray()).ToLower();
return clean.SequenceEqual(clean.Reverse());
}
}
var box = new Box<string>();
box.Add("hello");
Console.WriteLine(box.First() + " " + box.Count); // hello 1
Console.WriteLine(MathHelper.Largest(new[] { 3, 9, 4 }) + " " + MathHelper.Largest(new[] { "pear", "apple" })); // 9 pear
Console.WriteLine("A man, a plan, a canal: Panama".IsPalindrome()); // True (called as if it were a built-in string method)
Extension methods add methods to existing types without changing them. All of LINQ (section 12) is built from extension methods.
9. Null safety
null means “no object”, and using it incorrectly is the most common runtime error in all languages (NullReferenceException). Modern C# has a feature, nullable reference types (switched on by <Nullable>enable</Nullable>), where the compiler warns you whenever something that might be null is used unsafely. A string promises “never null”; a string? admits “might be null”.
string? maybe = null;
Console.WriteLine(maybe?.Length); // (empty) ?. means: only continue if not null; the result is null
Console.WriteLine(maybe?.Length ?? 0); // 0 ?? supplies a default when the left side is null
maybe ??= "default"; // ??= assigns only when the variable is null
Console.WriteLine(maybe); // default
int? score = null; // nullable VALUE type: an int that can also be "no value"
Console.WriteLine(score.HasValue + " " + score.GetValueOrDefault(-1)); // False -1
score = 80;
Console.WriteLine(score.Value + 1); // 81
void Register(string? email)
{
ArgumentNullException.ThrowIfNull(email); // fail early with a clear message
Console.WriteLine("registered " + email);
}
try { Register(null); }
catch (ArgumentNullException e) { Console.WriteLine("rejected: " + e.ParamName); } // rejected: email
Treat compiler warnings about nullability as real problems. The “null-forgiving” operator ! (as in name!) silences the warning and is a promise that you know better: use it rarely.
10. Pattern matching
Patterns test the shape of data and pull values out of it in one step. They make long if chains short and readable.
object[] things = { 42, "hello", 3.14, null, new int[] { 1, 2, 3 }, new Point(0, 5) };
foreach (object? thing in things)
{
string text = thing switch
{
null => "nothing",
int n when n > 40 => $"a big int: {n}",
int n => $"an int: {n}",
string s => $"a string of length {s.Length}",
double d => $"a double: {d}",
int[] { Length: > 0 } arr => $"an array starting with {arr[0]}",
Point { X: 0 } p => $"a point on the Y axis at {p.Y}", // property pattern
_ => "something else"
};
Console.WriteLine(text);
}
// a big int: 42 / a string of length 5 / a double: 3.14 / nothing / an array starting with 1 / a point on the Y axis at 5
int[] sample = { 1, 2, 3 };
if (sample is [1, .., 3]) // list pattern (C# 11): first is 1, last is 3
Console.WriteLine("starts with 1, ends with 3"); // starts with 1, ends with 3
object o = "text";
if (o is string str && str.Length > 2) // test the type AND get a typed variable
Console.WriteLine(str.ToUpper()); // TEXT
Console.WriteLine(o is not null); // True
11. Exceptions and cleanup
When something goes wrong at run time, .NET throws an exception. If nothing catches it, the program stops with a stack trace. Handle exceptions where you can do something sensible about them.
public class InsufficientFundsException(decimal balance, decimal requested)
: Exception($"Balance {balance} is less than {requested}")
{
public decimal Balance { get; } = balance;
}
public class BankAccount
{
public decimal Balance { get; private set; }
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount), "must be positive");
Balance += amount;
}
public void Withdraw(decimal amount)
{
if (amount > Balance) throw new InsufficientFundsException(Balance, amount);
Balance -= amount;
}
}
var account = new BankAccount();
account.Deposit(50);
try
{
account.Withdraw(80);
}
catch (InsufficientFundsException e) when (e.Balance < 100) // "when" adds a condition to a catch
{
Console.WriteLine("Refused: " + e.Message); // Refused: Balance 50 is less than 80
}
catch (Exception e) // the general catch goes LAST
{
Console.WriteLine("Unexpected: " + e.Message);
throw; // "throw;" rethrows and keeps the original stack trace
}
finally
{
Console.WriteLine("finally always runs"); // finally always runs
}
try { int.Parse("x"); }
catch (FormatException e) { Console.WriteLine(e.GetType().Name); } // FormatException
Rules: catch specific exceptions; never write an empty catch; use throw;, not throw e;, which destroys the stack trace; and do not use exceptions for normal flow (use TryParse, not try { Parse }).
using: releasing resources
Files, database connections and network sockets must be closed. Types that hold such resources implement IDisposable, and using guarantees Dispose() is called, even if an exception happens.
public class Connection : IDisposable
{
public Connection() => Console.WriteLine("open");
public void Query() => Console.WriteLine("querying");
public void Dispose() => Console.WriteLine("closed");
}
using (var one = new Connection()) // classic form: disposed at the closing brace
{
one.Query();
}
using var two = new Connection(); // the using DECLARATION: disposed at the end of the surrounding block
two.Query();
Console.WriteLine("end of block");
// open / querying / closed / open / querying / end of block / closed
12. LINQ: querying collections
LINQ (Language Integrated Query) gives you a SQL-like toolbox for any collection: filter, sort, group, join and calculate with short, readable code. It is the feature C# developers miss most when they use other languages. We will query a list of Employee records (defined in section 7).
var staff = new List<Employee>
{
new("Sara", "IT", 7800m),
new("Omar", "Sales", 6500m),
new("Lina", "Sales", 5200m),
new("Youssef", "IT", 9100m),
new("Nora", "IT", 4800m),
new("Hamza", "HR", 4500m),
};
var itStaff = staff.Where(e => e.Department == "IT").OrderByDescending(e => e.Salary); // filter + sort
Console.WriteLine(string.Join(", ", itStaff.Select(e => e.Name))); // Youssef, Sara, Nora
Console.WriteLine(staff.Sum(e => e.Salary) + " " + staff.Average(e => e.Salary).ToString("F2") + " " + staff.Max(e => e.Salary));
// 37900 6316.67 9100
Console.WriteLine(staff.Count(e => e.Salary > 5000) + " " + staff.Any(e => e.Department == "HR") + " " + staff.All(e => e.Salary > 4000)); // 4 True True
Console.WriteLine(staff.First(e => e.Department == "Sales").Name + " " + (staff.FirstOrDefault(e => e.Department == "Legal")?.Name ?? "none")); // Omar none
Console.WriteLine(staff.MaxBy(e => e.Salary)!.Name + " " + string.Join(",", staff.Select(e => e.Name).Skip(1).Take(2))); // Youssef Omar,Lina
foreach (var g in staff.GroupBy(e => e.Department).OrderBy(g => g.Key)) // GROUP BY
Console.WriteLine($"{g.Key}: {g.Count()} people, total {g.Sum(e => e.Salary)}");
// HR: 1 people, total 4500 / IT: 3 people, total 21700 / Sales: 2 people, total 11700
var byName = staff.ToDictionary(e => e.Name, e => e.Salary); // list to dictionary
Console.WriteLine(byName["Lina"]); // 5200
var depts = new[] { new { Code = "IT", Floor = 3 }, new { Code = "HR", Floor = 1 } }; // anonymous objects
var joined = staff.Join(depts, e => e.Department, d => d.Code, (e, d) => new { e.Name, d.Floor }); // an inner JOIN
Console.WriteLine(string.Join(", ", joined.Select(j => $"{j.Name}@{j.Floor}"))); // Sara@3, Youssef@3, Nora@3, Hamza@1
var query = from e in staff where e.Salary > 6000 orderby e.Name select e.Name; // the SQL-like "query syntax"
Console.WriteLine(string.Join(" ", query)); // Omar Sara Youssef
Console.WriteLine(string.Join(" ", Enumerable.Range(1, 10).Where(n => n % 3 == 0).Select(n => n * n))); // 9 36 81
Console.WriteLine(string.Join(" ", new[] { 3, 1, 3, 2, 1 }.Distinct().OrderBy(n => n))); // 1 2 3
Deferred execution
Most LINQ methods are lazy: they describe a query but do not run it until you enumerate the result with foreach, ToList(), Count() and so on. That is powerful (it can stop early and handle huge data) and a source of surprises:
var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1); // nothing has run yet
numbers.Add(4); // changing the source BEFORE enumerating changes the result
Console.WriteLine(string.Join(",", query)); // 2,3,4
var snapshot = numbers.Where(n => n > 1).ToList(); // ToList() runs it now and stores the result
numbers.Add(5);
Console.WriteLine(snapshot.Count); // 3
Do not enumerate the same lazy query many times (it re-runs every time); store it with ToList() when you need the results more than once. With Entity Framework, a LINQ query is translated to SQL and runs in the database, so the same rules decide when the query is sent.
13. Delegates, lambdas and events
A delegate is a variable that holds a method. Func<...> is a delegate that returns a value, Action<...> one that does not, and Predicate<T> one that returns a bool. A lambda (x => x * 2) is a compact way to write a method inline. LINQ is full of them.
Func<int, int> square = x => x * x;
Func<int, int, int> add = (a, b) => a + b;
Action<string> shout = s => Console.WriteLine(s.ToUpper() + "!");
Predicate<int> isEven = n => n % 2 == 0;
Console.WriteLine(square(7) + " " + add(2, 3) + " " + isEven(10)); // 49 5 True
shout("hello"); // HELLO!
List<int> Apply(List<int> items, Func<int, int> transform) => items.Select(transform).ToList();
Console.WriteLine(string.Join(",", Apply([1, 2, 3], x => x * 10))); // 10,20,30 (the behaviour is passed in as an argument)
int factor = 3;
Func<int, int> times = x => x * factor; // a lambda can "capture" variables around it
factor = 5;
Console.WriteLine(times(2)); // 10: it sees the CURRENT value of factor
Events
An event lets one object announce that something happened, while other objects subscribe without the first one knowing who they are.
public class Thermostat
{
public event EventHandler<double>? TemperatureChanged; // the event: subscribers attach handlers to it
private double _temperature;
public double Temperature
{
get => _temperature;
set
{
if (value == _temperature) return;
_temperature = value;
TemperatureChanged?.Invoke(this, value); // tell everybody who is subscribed (if anyone is)
}
}
}
var thermostat = new Thermostat();
thermostat.TemperatureChanged += (sender, t) => Console.WriteLine($"now {t} degrees"); // subscribe
thermostat.TemperatureChanged += (sender, t) => { if (t > 30) Console.WriteLine("too hot!"); };
thermostat.Temperature = 22; // now 22 degrees
thermostat.Temperature = 35; // now 35 degrees / too hot!
14. Async and await
Many operations spend most of their time waiting: a web request, a file, a database. If your code simply waits, the thread is stuck and cannot do anything else (in a web server, that means fewer users served; in a desktop app, a frozen window). async and await let the thread go and do other work while waiting, and resume afterwards, all in code that still reads top to bottom.
async Task<string> FetchAsync(string name, int delayMs)
{
await Task.Delay(delayMs); // a stand-in for a network or database call: the thread is FREE while waiting
return $"{name} done";
}
Console.WriteLine(await FetchAsync("a", 50)); // a done
var started = DateTime.UtcNow;
Task<string> t1 = FetchAsync("one", 200); // start them all first...
Task<string> t2 = FetchAsync("two", 150);
Task<string> t3 = FetchAsync("three", 100);
string[] results = await Task.WhenAll(t1, t2, t3); // ...then wait for all of them together
Console.WriteLine(string.Join(", ", results)); // one done, two done, three done
Console.WriteLine((DateTime.UtcNow - started).TotalMilliseconds < 450); // True: about 200 ms in total, not 450
int result = await Task.Run(() => Enumerable.Range(1, 1000).Sum()); // push CPU-heavy work to a pool thread
Console.WriteLine(result); // 500500
Cancelling and handling errors
async Task SlowWorkAsync(CancellationToken token)
{
for (int i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested(); // cooperative cancellation
await Task.Delay(20, token);
}
}
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); // cancel automatically after 100 ms
try { await SlowWorkAsync(cts.Token); }
catch (OperationCanceledException) { Console.WriteLine("cancelled"); } // cancelled
async Task FailAsync() { await Task.Delay(10); throw new InvalidOperationException("boom"); }
try { await FailAsync(); } // exceptions flow through await like normal code
catch (InvalidOperationException e) { Console.WriteLine("caught " + e.Message); } // caught boom
Rules that save you hours: name async methods with the Async suffix; use await all the way, and avoid .Result and .Wait(), which can freeze the application; never write async void except for event handlers, because its exceptions cannot be caught; and accept a CancellationToken in methods that can take long. A real HTTP call looks like this (not run here because it needs the internet):
using var http = new HttpClient(); // create ONE HttpClient and reuse it in a real application
http.Timeout = TimeSpan.FromSeconds(10);
string html = await http.GetStringAsync("https://example.com");
Console.WriteLine(html.Length);
var response = await http.GetAsync("https://api.github.com/repos/dotnet/runtime");
response.EnsureSuccessStatusCode(); // throws for 4xx and 5xx
string body = await response.Content.ReadAsStringAsync();
15. Files, JSON and dates
string folder = Path.Combine(Path.GetTempPath(), "csharp-tutorial-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, "notes.txt"); // Path.Combine picks the right separator
File.WriteAllText(file, "first line\nsecond line\n");
File.AppendAllText(file, "third line\n");
string[] lines = File.ReadAllLines(file);
Console.WriteLine(lines.Length + " " + lines[2] + " " + File.Exists(file) + " " + Path.GetFileName(file) + " " + Path.GetExtension(file));
// 3 third line True notes.txt .txt
using (var reader = new StreamReader(file)) // read big files line by line
{
string? line;
while ((line = reader.ReadLine()) != null)
Console.Write(line.Length + " "); // 10 11 10
}
Console.WriteLine();
await File.WriteAllTextAsync(Path.Combine(folder, "async.txt"), "written asynchronously");
Console.WriteLine(Directory.GetFiles(folder).Length); // 2
Directory.Delete(folder, recursive: true); // careful: deletes everything inside
Console.WriteLine(Directory.Exists(folder)); // False
JSON with System.Text.Json
public record Product(string Name, decimal Price, List<string> Tags);
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = false, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var product = new Product("Tea", 3.5m, ["drink", "hot"]);
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json); // {"name":"Tea","price":3.5,"tags":["drink","hot"]}
Product? back = JsonSerializer.Deserialize<Product>(json, options);
Console.WriteLine(back == product); // False: the Tags list is a different list object, and records compare list REFERENCES
Console.WriteLine(back!.Name + " " + back.Price + " " + back.Tags.Count); // Tea 3.5 2
using JsonDocument doc = JsonDocument.Parse("""{ "user": { "name": "Sara", "roles": ["admin", "dev"] } }""");
Console.WriteLine(doc.RootElement.GetProperty("user").GetProperty("roles")[1].GetString()); // dev
Use Deserialize<T> when you know the shape of the data and JsonDocument to read bits of unknown JSON. System.Text.Json ships with .NET: no extra package needed.
Dates and times
using System.Globalization;
var date = new DateOnly(2026, 10, 30); // a date with no time of day (.NET 6+)
Console.WriteLine(date.DayOfWeek + " " + date.AddDays(45) + " " + date.ToString("yyyy-MM-dd")); // Friday 12/14/2026 2026-10-30
var moment = new DateTime(2026, 10, 30, 14, 30, 0, DateTimeKind.Utc);
Console.WriteLine(moment.ToString("yyyy-MM-dd HH:mm") + " " + moment.AddHours(10).Hour); // 2026-10-30 14:30 0
TimeSpan span = new DateOnly(2026, 12, 25).ToDateTime(TimeOnly.MinValue) - date.ToDateTime(TimeOnly.MinValue);
Console.WriteLine(span.TotalDays + " days"); // 56 days
DateTime parsed = DateTime.ParseExact("25/12/2026", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(parsed.Month); // 12
Console.WriteLine(DateTimeOffset.UtcNow.Offset); // 00:00:00
Store and exchange times in UTC (DateTimeOffset.UtcNow) and convert to local time only for display. Use TimeZoneInfo for time zones.
16. Projects, NuGet, dependency injection and tests
A solution groups projects; a project builds one program or library. Code is organised into namespaces (namespace MyApp.Billing;) and split over files, one main type per file. Libraries come from NuGet, the .NET package manager.
dotnet new sln -n Shop # a solution
dotnet new classlib -o Shop.Core # a library project
dotnet new console -o Shop.App
dotnet sln add Shop.Core Shop.App
dotnet add Shop.App reference Shop.Core # one project uses another
dotnet add Shop.App package Serilog # install a NuGet package
dotnet list package --outdated # which packages have updates?
dotnet restore # download the packages in the project files
dotnet new xunit -o Shop.Tests # a test project
dotnet add Shop.Tests reference Shop.Core
dotnet test # run all tests
Dependency injection
You saw it in the interface example: OrderService asks for an INotifier in its constructor and does not create one. A DI container builds the objects and passes in what they need, so you configure the wiring in one place. It is built into ASP.NET Core and available for any app through the Microsoft.Extensions.DependencyInjection package.
// dotnet add package Microsoft.Extensions.DependencyInjection
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddSingleton<INotifier, ConsoleNotifier>(); // one shared instance
services.AddTransient<OrderService>(); // a new instance each time it is requested
using var provider = services.BuildServiceProvider();
var orders = provider.GetRequiredService<OrderService>(); // the container builds OrderService and supplies the notifier
orders.Place("lina@example.com"); // [console] to lina@example.com: Your order is confirmed
public interface INotifier { void Send(string to, string message); }
public class ConsoleNotifier : INotifier { public void Send(string to, string message) => Console.WriteLine($"[console] to {to}: {message}"); }
public class OrderService(INotifier notifier) { public void Place(string customer) => notifier.Send(customer, "Your order is confirmed"); }
Unit tests
A test project with xUnit keeps your code honest. Interfaces make this easy: in a test you hand the class a fake instead of the real mailer or database.
using Xunit;
public class OrderServiceTests
{
[Fact]
public void Place_sends_one_confirmation()
{
var fake = new FakeNotifier();
var service = new OrderService(fake);
service.Place("omar@example.com");
Assert.Single(fake.Sent);
Assert.Equal("omar@example.com:Your order is confirmed", fake.Sent[0]);
}
[Theory]
[InlineData("a@b.com")]
[InlineData("c@d.com")]
public void Place_works_for_any_customer(string customer)
{
var fake = new FakeNotifier();
new OrderService(fake).Place(customer);
Assert.Contains(customer, fake.Sent[0]);
}
}
17. A web API with ASP.NET Core
ASP.NET Core is the framework for web sites and APIs. Since .NET 6, a complete API fits in one file thanks to minimal APIs. Create it with dotnet new web -o Api and replace Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<TodoStore>(); // register the store with the DI container
var app = builder.Build();
app.MapGet("/", () => "Todo API is running");
app.MapGet("/todos", (TodoStore store) => store.All()); // returns JSON automatically
app.MapGet("/todos/{id:int}", (int id, TodoStore store) =>
store.Find(id) is { } todo ? Results.Ok(todo) : Results.NotFound());
app.MapPost("/todos", (NewTodo input, TodoStore store) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
return Results.BadRequest("Title is required");
var created = store.Add(input.Title);
return Results.Created($"/todos/{created.Id}", created);
});
app.MapDelete("/todos/{id:int}", (int id, TodoStore store) => store.Remove(id) ? Results.NoContent() : Results.NotFound());
app.Run();
public record NewTodo(string Title);
public record Todo(int Id, string Title, bool Done);
public class TodoStore
{
private readonly List<Todo> _items = [new(1, "Learn C#", false)];
private int _nextId = 2;
public IReadOnlyList<Todo> All() => _items;
public Todo? Find(int id) => _items.FirstOrDefault(t => t.Id == id);
public Todo Add(string title) { var t = new Todo(_nextId++, title, false); _items.Add(t); return t; }
public bool Remove(int id) => _items.RemoveAll(t => t.Id == id) > 0;
}
dotnet run
curl http://localhost:5000/todos
curl -X POST http://localhost:5000/todos -H "Content-Type: application/json" -d '{"title":"Write tests"}'
The port is printed when the app starts. Parameters are filled in automatically from the route ({id}), the JSON body (NewTodo) and the DI container (TodoStore). For larger applications, ASP.NET Core also offers controllers, authentication, validation, Swagger/OpenAPI and background services. To publish on a Linux server (such as the RHEL machines in our Linux guide), run dotnet publish -c Release, copy the output, and run it as a systemd service behind Nginx or Apache.
18. Databases
C# talks to databases in two main ways. ADO.NET (with Microsoft.Data.SqlClient for SQL Server) sends your SQL and returns rows: you control everything. Entity Framework Core maps tables to classes and translates LINQ into SQL for you. Either way, always use parameters, never string concatenation, to prevent SQL injection.
// dotnet add package Microsoft.Data.SqlClient
using Microsoft.Data.SqlClient;
string connectionString = "Server=localhost;Database=SalesDB;Integrated Security=true;TrustServerCertificate=true";
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var command = new SqlCommand(
"SELECT TOP (10) CustomerId, Name FROM dbo.Customers WHERE Country = @country ORDER BY Name", connection);
command.Parameters.AddWithValue("@country", "Morocco"); // a parameter: the safe way
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
Console.WriteLine($"{reader.GetInt32(0)}: {reader.GetString(1)}");
// dotnet add package Microsoft.EntityFrameworkCore.SqlServer
using Microsoft.EntityFrameworkCore;
await using var db = new ShopContext();
var customers = await db.Customers.Where(c => c.Country == "Morocco").OrderBy(c => c.Name).Take(10).ToListAsync(); // becomes SQL
foreach (var c in customers) Console.WriteLine(c.Name);
// type declarations go AFTER the top-level statements
public class Customer { public int CustomerId { get; set; } public string Name { get; set; } = ""; public string Country { get; set; } = ""; }
public class ShopContext : DbContext
{
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnConfiguring(DbContextOptionsBuilder options) =>
options.UseSqlServer("Server=localhost;Database=SalesDB;Integrated Security=true;TrustServerCertificate=true");
}
These two snippets need a database, so they are not run here. When a query is slow, look at the SQL that is actually sent and at the execution plan: our guides on slow SQL Server queries and indexes explain how. For permissions, see least-privilege logins: your application should connect with an account that has only the rights it needs, never sa.
19. A complete small project
Here is a small but real program that combines classes, interfaces, records, LINQ, JSON, exceptions and a menu-free command style. It is an expense tracker: it stores expenses in a JSON file and reports the totals by category.
public record Expense(DateOnly Date, string Category, decimal Amount, string Note);
public interface IExpenseStore
{
List<Expense> Load();
void Save(IEnumerable<Expense> expenses);
}
public class JsonExpenseStore(string path) : IExpenseStore
{
private static readonly System.Text.Json.JsonSerializerOptions Options = new() { WriteIndented = true };
public List<Expense> Load() =>
File.Exists(path)
? System.Text.Json.JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(path), Options) ?? []
: [];
public void Save(IEnumerable<Expense> expenses) =>
File.WriteAllText(path, System.Text.Json.JsonSerializer.Serialize(expenses, Options));
}
public class ExpenseTracker(IExpenseStore store)
{
private readonly List<Expense> _expenses = store.Load();
public void Add(DateOnly date, string category, decimal amount, string note)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive");
if (string.IsNullOrWhiteSpace(category)) throw new ArgumentException("Category is required", nameof(category));
_expenses.Add(new Expense(date, category.Trim(), amount, note));
store.Save(_expenses);
}
public decimal Total() => _expenses.Sum(e => e.Amount);
public IEnumerable<(string Category, decimal Total, int Count)> ByCategory() =>
_expenses.GroupBy(e => e.Category)
.Select(g => (g.Key, g.Sum(e => e.Amount), g.Count()))
.OrderByDescending(x => x.Item2);
public IEnumerable<Expense> Month(int year, int month) =>
_expenses.Where(e => e.Date.Year == year && e.Date.Month == month).OrderBy(e => e.Date);
}
string path = Path.Combine(Path.GetTempPath(), $"expenses-{Guid.NewGuid():N}.json");
var tracker = new ExpenseTracker(new JsonExpenseStore(path));
tracker.Add(new DateOnly(2026, 10, 2), "Food", 42.50m, "Groceries");
tracker.Add(new DateOnly(2026, 10, 5), "Transport", 12.00m, "Taxi");
tracker.Add(new DateOnly(2026, 10, 9), "Food", 18.25m, "Lunch");
tracker.Add(new DateOnly(2026, 11, 1), "Rent", 600.00m, "November");
try { tracker.Add(new DateOnly(2026, 10, 10), "Food", -5m, "oops"); }
catch (ArgumentOutOfRangeException e) { Console.WriteLine("Rejected: " + e.ParamName); } // Rejected: amount
Console.WriteLine($"Total: {tracker.Total():F2}"); // Total: 672.75
foreach (var (category, total, count) in tracker.ByCategory())
Console.WriteLine($"{category,-10} {total,8:F2} ({count})");
// Rent 600.00 (1)
// Food 60.75 (2)
// Transport 12.00 (1)
Console.WriteLine(string.Join(" | ", tracker.Month(2026, 10).Select(e => $"{e.Date:MM-dd} {e.Note}"))); // 10-02 Groceries | 10-05 Taxi | 10-09 Lunch
var reloaded = new ExpenseTracker(new JsonExpenseStore(path)); // the data survived: it was saved in the file
Console.WriteLine(reloaded.Total()); // 672.75
File.Delete(path);
Extend it: read commands from the command line, add an Update and Delete, export a CSV report, replace the JSON store with SQLite or SQL Server (just implement IExpenseStore again, and nothing else changes), then wrap it in the web API from section 17. That swap-without-changing-anything property is the practical value of interfaces.
20. Good habits, mistakes, and C# compared with Python
Habits of good C# code
- Follow the naming conventions:
PascalCasefor types, methods, properties and public members;camelCasefor local variables and parameters;_camelCasefor private fields;INamefor interfaces. - Keep nullable reference types on and fix the warnings.
- Prefer immutability:
readonly,initand records make code easier to reason about. - Depend on interfaces, inject them through the constructor, and keep classes small with one job.
- Use
asyncfor all I/O, passCancellationTokens, and never block on tasks. - Use
decimalfor money,DateTimeOffsetor UTC for time, and culture-invariant formatting for data. - Let tools help: turn on analyzers, use
dotnet format, and write tests for the logic that matters.
Mistakes everybody makes once
- Comparing floating-point numbers with
==. UseMath.Abs(a - b) < 1e-9, ordecimal. - Integer division:
5 / 2is2. Make one side adouble. - Using
+=on strings in a big loop, instead of aStringBuilder. - Forgetting to dispose connections and streams: use
using. - Enumerating a lazy LINQ query repeatedly, re-running it each time.
- Changing a collection while looping over it with
foreach(it throwsInvalidOperationException): loop over a copy (.ToList()) or build a new collection. async void,.Resultand.Wait().- Catching
Exceptionand swallowing it, orthrow ex;instead ofthrow;. - Creating a new
HttpClientfor every request, which exhausts connections: reuse one (or useIHttpClientFactory).
C# and Python side by side
| Idea | Python | C# |
|---|---|---|
| Typing | Dynamic: types are checked while running | Static: the compiler checks types before running |
| Blocks | Indentation | Curly braces and semicolons |
| Run it | python app.py |
dotnet run (compiled to IL) |
| List and dictionary | [1, 2], {"a": 1} |
List<int>, Dictionary<string,int> |
| Comprehension | [n*n for n in xs if n > 1] |
xs.Where(n => n > 1).Select(n => n*n) |
| String formatting | f"{x:.2f}" |
$"{x:F2}" |
| No value | None |
null (with nullable checks) |
| Data class | @dataclass |
record |
| Interfaces | Duck typing, abc, protocols |
interface, checked by the compiler |
| Resources | with open(...) |
using var f = ... |
| Async | async def / await / asyncio |
async Task / await |
| Packages | pip, PyPI |
dotnet add package, NuGet |
| Best at | Scripts, data, quick tools | Large business apps, services, performance |
Quick answers
What is the difference between .NET, .NET Framework and .NET Core? .NET Framework (up to 4.8) is the old Windows-only platform, still maintained. .NET Core was the rewrite that became simply .NET (version 5 and later). New projects should use current .NET.
C# or Java? They are very similar. C# has had more modern language features (LINQ, async/await, records, pattern matching) and is the usual choice with Microsoft technology, Azure and Unity; Java is strong in the Android and enterprise Linux world. Learning one makes the other easy.
Do I need Windows? No. .NET runs on Linux and macOS, and Visual Studio Code works everywhere. Only Windows desktop technologies (WPF, WinForms) are Windows-only.
What should I build next? The expense tracker above, then a web API for it, then add SQL Server storage. Read the official Microsoft Learn documentation (learn.microsoft.com/dotnet), which includes free interactive courses, and practise algorithms on a site like Exercism or LeetCode, using our algorithms tutorial to understand the ideas first.
