Examples

C# examples

Build typed applications on .NET.

40 examples

C# Basics

Print a value from a .NET program.

C#

C# Loops

Repeat an action with a for loop.

C#

C# Methods

Package reusable logic in a static method.

C#

C# strings and formatting

Use common string methods, compare text correctly, and format numbers with format specifiers.

C#

C# exceptions, finally, and using

Throw and catch a custom exception, filter by condition, and release resources reliably.

C#

C# nullable values, patterns, and switch expressions

Handle missing values safely and branch on the type and value of an object.

C#

C# Classes and Properties

Protect state with a property that only the class can change.

C#

C# inheritance, virtual, and abstract members

Override behaviour in subclasses and call it through a base-type reference.

C#

C# records, with-expressions, and value semantics

Create immutable data types with value equality, copy them with changes, and compare with structs and classes.

C#

C# delegates, events, and lambdas

Pass behaviour as a value and let objects notify subscribers when something happens.

C#

C# Lists

Grow a collection with List<T> and add its values.

C#

C# Dictionary and HashSet operations

Count words with a dictionary and combine sets with union, intersection, and difference.

C#

C# Stack and Queue: evaluating postfix expressions

Use a stack to evaluate expressions written in reverse Polish notation and a queue for first-in order.

C#

C# sorting, stability, and Array.BinarySearch

Sort arrays and records, keep equal items in order with LINQ, and find insertion points.

C#

C# LRU cache with Dictionary and LinkedList

Combine a hash table and a doubly linked list so that get, put, and eviction all take constant time.

C#

C# generic binary search tree with IEnumerable

Constrain the element type with IComparable<T> and expose the sorted values with yield return.

C#

C#: best and worst case of insertion sort

Count comparisons on sorted, reversed, and mixed input to see how input order changes the cost.

C#

C#: watching List<T> grow geometrically

Observe the capacity of a List<int> as items are added and see that reallocations become rarer.

C#

C#: relational queries with LINQ join and group

Join two collections on a key, sort the result, and aggregate it by group, as SQL does.

C#

C#: an ordered index with SortedSet

Answer range, minimum, maximum, and nearest-value queries on sorted keys.

C#

C#: first-come-first-served versus shortest-job-first

Compare the average waiting time of two scheduling policies for the same set of jobs.

C#

C#: protecting shared state with lock

Start two threads that update one counter and use lock so that no update is lost.

C#

C#: a TCP echo server on the loopback interface

Use TcpListener and TcpClient with async methods to send a line and read the reply.

C#

C#: IPv4 subnets with IPAddress and bit masks

Compute the network and broadcast addresses for a CIDR block and test whether addresses belong to it.

C#

C#: testing values and exceptions with a small harness

Check results, and verify that bad input throws the expected exception type.

C#

C#: dependency injection makes code testable

Pass a dependency in through the constructor so tests can replace it with a fixed one.

C#

C#: message authentication with HMAC-SHA256

Compute a keyed tag so a receiver can detect tampering, and compare tags safely.

C#

C#: password storage with a salt and PBKDF2

Derive a slow salted hash from a password and verify a login attempt in constant time.

C#

C#: running tasks in parallel with Task.WhenAll

Start independent computations as tasks and await all of their results.

C#

C#: Parallel.For with Interlocked

Spread loop iterations over cores and combine results safely with an atomic add.

C#

C#: uniform-cost search with PriorityQueue

Find the cheapest route from a start node to every other node in a weighted graph.

C#

C#: solving tic-tac-toe with minimax

Search the complete game tree and show that perfect play by both sides ends in a draw.

C#

C#: first-order unification

Find a substitution that makes two logical terms identical, including the occurs check.

C#

C#: semantic networks with default reasoning

Inherit properties up an is-a hierarchy and let more specific nodes override defaults.

C#

C#: logistic regression for classification

Predict a probability with the sigmoid function and train the weights by gradient descent.

C#

C#: entropy and information gain for decision trees

Measure how much a feature reduces uncertainty about a label, the criterion used to choose a split.

C#

C#: backpropagation learns XOR

Train a 2-2-1 sigmoid network by gradient descent until it computes XOR.

C#

C#: activation functions and their ranges

Compare sigmoid, tanh, and ReLU on the same inputs.

C#

C#: Sobel gradient magnitude on a diagonal edge

Combine horizontal and vertical Sobel responses into one edge-strength value.

C#

C#: the integral image (summed-area table)

Precompute running sums so that the total of any rectangle takes four lookups.

C#