C# by Examples

Practical C# code snippets — short, copy-paste ready, and organized by topic.

How to use async and await in C#

Learn how async and await enable asynchronous programming in C#, letting methods suspend execution without blocking the calling thread.

When to Use async/await vs Task.Run in C#

Learn when to use async/await for I/O-bound work versus Task.Run for CPU-bound code that needs to run on a background thread in C#.

C# casting and type conversion — explicit cast, as, is, Convert, implicit

Learn how to cast and convert types in C#. Covers explicit cast, implicit conversion, the as and is operators, Convert class, safe casting patterns, and when each approach is appropriate.

How to check if string is null or empty

Use string.IsNullOrEmpty() to check for null or empty strings in C#. Use string.IsNullOrWhiteSpace() to also catch whitespace-only strings.

C# checked and unchecked — integer overflow explained

Integer overflow in C# silently wraps by default. Learn how checked and unchecked contexts work, when to use them, and how to handle arithmetic overflow safely.

C# collections guide — List, Array, Dictionary, HashSet, Queue, Stack

Which C# collection should you use? Compare List, Array, Dictionary, HashSet, Queue, Stack, and LinkedList with Big-O complexity, use cases, and code examples.

When to Use const vs readonly in C#

const fields are compile-time constants set at declaration. readonly fields are runtime constants that can be assigned in the constructor in C#.

How to convert int to enum in C#

Cast an int to an enum type in C# for a direct conversion. Learn how to safely convert integers to enum values using Enum.IsDefined and Enum.TryParse.

How to convert string to int in C#

Use int.Parse() when the string is trusted, or int.TryParse() for safe conversion without exceptions when parsing strings to integers in C#.

How to format DateTime in C#

Format DateTime values in C# using ToString() with standard or custom format strings. Use specifiers like d for short date or T for long time.

Delegates, lambdas, Func, and Action in C#

Learn delegates, lambda expressions, Func<T>, Action<T>, and Predicate<T> in C# with practical examples. Understand how lambdas replace verbose delegate syntax and enable LINQ.

C# Dictionary guide — add, lookup, iterate, and common patterns

A complete guide to Dictionary<TKey,TValue> in C#: adding and updating entries, TryGetValue, ContainsKey, iterating keys and values, removing entries, and common patterns like counting and grouping.

When to Use Dictionary vs Hashtable in C#

Dictionary<TKey, TValue> is a generic, type-safe modern collection. Hashtable is a legacy non-generic alternative that stores objects and requires casting.

C# enum guide — declare, iterate, Flags, and convert to string

A complete guide to C# enums: declaring enums, getting all values with Enum.GetValues, iterating, Flags attribute for bit fields, converting to string, and parsing enum values.

C# events — EventHandler, custom EventArgs, raise and subscribe to events

Learn how C# events work: declaring events with EventHandler, raising events, subscribing and unsubscribing, creating custom EventArgs, and safe event invocation patterns.

C# Exception Handling — throw, custom exceptions, and exception filters

Go beyond basic try/catch in C#: throw vs rethrow, creating custom exception classes, exception filters with when, and best practices for exception handling in production code.

When to Use foreach vs for Loop in C#

foreach is more readable for simple collection traversal. for loops provide index access, reverse iteration, and custom step sizes for more control in C#.

How to generate random numbers in C#

Generate random numbers in C# using the Random class. In .NET 6+, use Random.Shared for a static, thread-safe shared instance with better performance.

C# Generics — generic classes, methods, and constraints explained

C# generics let you write type-safe, reusable code without casting or boxing. Learn how to create generic classes, generic methods, and apply constraints with the where keyword.

C# GUID — generate, parse, format, and compare GUIDs

Learn how to generate, parse, format, and compare GUIDs in C#. Covers Guid.NewGuid(), Guid.Parse(), TryParse, ToString formats, Guid.Empty, and performance tips.

When to Use HashSet vs List in C#

HashSet<T> is optimized for fast lookups and uniqueness. List<T> is ordered, allows duplicates, and provides index access. Learn which to use in C#.

When to Use IEnumerable vs IQueryable in C#

IEnumerable<T> processes queries in memory on local collections. IQueryable<T> translates queries to SQL or other native languages for remote data sources.

When to Use Interface vs Abstract Class in C#

Interfaces define a pure contract with no implementation. Abstract classes share a base with common code. Learn when to use each design pattern in C#.

C# interfaces — define, implement, explicit implementation, and interface vs abstract class

Learn how C# interfaces work: defining members, implementing multiple interfaces, explicit interface implementation, default interface methods, and when to use interfaces vs abstract classes.

How to iterate over a dictionary

Iterate a Dictionary in C# using a foreach loop to access each KeyValuePair, or loop over just the Keys or Values collection properties separately.

How to join strings in C#

Use string.Join() in C# to concatenate collection elements with a separator. More efficient than using + in a loop and works with any IEnumerable.

LINQ aggregate methods in C# — Sum, Count, Average, Min, Max, Aggregate

Use LINQ aggregate methods in C# to compute sums, counts, averages, min/max, and custom reductions. Covers Sum(), Count(), Average(), Min(), Max(), and the general-purpose Aggregate() method.

How to find elements in a list with LINQ in C#

Use LINQ methods like First, FirstOrDefault, Single, and Any to find elements in C# collections. Learn when to use each to avoid InvalidOperationException.

How to use LINQ GroupBy in C#

Use LINQ GroupBy() in C# to group elements by a key selector. Returns groups each containing the key and matching elements from the source collection.

How to join collections with LINQ in C#

Use LINQ Join() in C# to combine two sequences on a matching key, equivalent to SQL inner join. Only elements with matching keys appear in the result.

How to sort with LINQ OrderBy in C#

Sort with LINQ OrderBy() in C# to get a new sorted sequence without modifying the original. Use ThenBy() for secondary sort keys.

How to use LINQ Select in C# (projection examples)

Use LINQ Select() in C# to project each element into a new form. Transforms a collection with a lambda and returns a new IEnumerable with the results.

How to filter collections with LINQ Where

Filter a collection in C# with LINQ Where() by passing a predicate function. Uses deferred execution and returns only elements satisfying the condition.

How to Check if a List is Empty

Check if a List is empty in C# using the Count property or LINQ Any() method. Prefer Any() for IEnumerable types to avoid full enumeration overhead.

When to use List vs Array in C#

Arrays have a fixed size and are memory-efficient in C#. Lists are dynamic, resize automatically, and provide methods like Add(), Remove(), and Contains().

How to Merge Two Lists

Merge two C# lists using LINQ Concat() for a clean readable result, or AddRange() to append elements directly into an existing list in place.

How to use the null coalescing operator in C#

The ?? operator returns the left operand if not null, otherwise the right. Use ??= to assign a default value only when the variable is null in C#.

How to use nullable reference types in C#

Nullable reference types in C# 8.0+ make nullability explicit to prevent NullReferenceException. Enable with the Nullable enable setting in your project.

C# nullable types — int?, Nullable<T>, null handling patterns

C# nullable value types (int?, bool?, DateTime?) let value types represent the absence of a value. Learn Nullable<T>, HasValue, Value, GetValueOrDefault, and common null-handling patterns.

When to use Parse vs TryParse in C#

Use int.Parse() when the string is guaranteed valid. Use int.TryParse() to safely handle potentially invalid input without throwing an exception in C#.

Pattern matching in C# — is, switch, property, and list patterns

A practical guide to pattern matching in C#: type patterns with is, constant patterns, property patterns, positional patterns, list patterns, and combining patterns with and/or/not.

C# properties — get, set, init, auto properties, and computed properties

Learn how C# properties work: auto properties, get/set accessors, init-only properties, computed properties, and the difference between properties and fields.

How to Read a Text File

Read a text file in C# with File.ReadAllLines() for simplicity, or File.ReadLines() for memory-efficient lazy reading of large files line by line.

C# record types — record vs class, with expressions, and immutability

C# records are reference types with built-in value equality, immutability, and a concise syntax. Learn how records compare to classes, how to use with expressions, and when to use record struct.

When to Use ref vs out Parameters in C#

ref parameters must be initialized before the call. out parameters must be assigned inside the method. Learn when to use each type of parameter in C#.

C# Regex — pattern matching, groups, replace, and examples

Use C# Regex to match, extract, and replace text with regular expressions. Covers IsMatch, Match, Groups, Replace, named captures, and compiled regex for performance.

How to remove duplicates from a list

Remove duplicates from a C# list using LINQ Distinct() or by converting to HashSet<T>, which automatically stores only unique element values.

How to sort a list by property in C#

Sort a list of objects by property in C# using LINQ OrderBy(), List.Sort() with a lambda, or IComparer. Covers ascending, descending, and multi-key sorting.

How to sort a list in C#

Sort a C# list with Sort() for in-place modification, or LINQ OrderBy() for a new sorted sequence that leaves the original list unchanged.

C# Span<T> and Memory<T> — zero-allocation slicing and high-performance buffers

Span<T> and Memory<T> let you slice arrays, strings, and stack buffers without allocating new objects. Learn how to use them to cut allocations, speed up parsing, and write modern high-performance C#.

C# Stack and Queue — push, pop, enqueue, dequeue, and when to use each

Learn how to use Stack<T> and Queue<T> in C#. Covers push/pop/peek for stacks, enqueue/dequeue/peek for queues, performance characteristics, and real-world use cases for each.

How to compare strings in C# — ==, Equals, StringComparison, OrdinalIgnoreCase

Compare strings in C# correctly using ==, .Equals(), or string.Compare(). Understand StringComparison, OrdinalIgnoreCase, CurrentCulture, and when to use each approach.

string.Format in C# — syntax, format specifiers, and examples

Learn string.Format in C# with practical examples: numeric format specifiers (C, D, F, N, P, X), date formatting, alignment, padding, and how it compares to string interpolation.

How to use string interpolation in C#

Use the $ prefix in C# for string interpolation to embed expressions in string literals. More readable than string.Format() and supports format specifiers.

C# string methods cheat sheet — Contains, Split, Replace, Trim, and more

A practical reference for the most common C# string methods: Contains, StartsWith, EndsWith, Split, Replace, Trim, Substring, IndexOf, and PadLeft/PadRight with examples.

What is the difference between String and string in C#

In C#, string (lowercase) is an alias for System.String. Both compile to the same IL code. Using the lowercase string keyword is the C# convention.

How to use StringBuilder in C#

Use StringBuilder in C# for efficient string building in loops. Unlike immutable strings, it reuses the same buffer to avoid repeated memory allocations.

When to Use Struct vs. Class

Use a struct for small simple value types like Point or Color. Use a class for complex types with behavior. Structs are stack-allocated value types in C#.

How to use switch expressions in C#

Switch expressions in C# 8.0+ provide concise pattern matching that returns a value directly. They replace verbose switch statements and eliminate break.

Task.WhenAll, Task.WhenAny, and Task.Run in C#

Learn how to run multiple async tasks concurrently with Task.WhenAll and Task.WhenAny, and when to use Task.Run to offload CPU-bound work in C#.

How to use try catch finally in C#

Handle exceptions in C# using try-catch-finally. Code in try runs first, catch handles exceptions, and finally always executes for resource cleanup.

When to Use Tuple vs ValueTuple in C#

Tuple is a reference type from older C# with Item1, Item2 properties. ValueTuple is a C# 7+ value type struct with named members and better performance.

When to Use var vs Explicit Types in C#

var lets the C# compiler infer the type from the initialization expression. Use explicit types when the type is not obvious from context or for clarity.

What is BOM Character in C#

A BOM (Byte Order Mark) is a Unicode character indicating a file's encoding and byte order. Learn how to detect and handle BOM characters in C# file I/O.

How to Write to a Text File in C#

Write to a text file in C# using File.WriteAllText, File.WriteAllLines, File.AppendAllText, StreamWriter, and async variants. Includes examples for creating, overwriting, and appending files.