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#.
Boyer-Moore string search algorithm in C# — fast pattern matching explained
Implement the Boyer-Moore string search algorithm in C# for fast pattern matching. Learn how Boyer-Moore works, when to use it over built-in methods, and see complete working examples with performance benchmarks.
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.
C# String to Int: Parse, TryParse, Convert, and Examples
Learn how to convert a string to int in C# with int.Parse, int.TryParse, and Convert.ToInt32. Handle null, empty, invalid, whitespace, and overflow input safely.
C# DateTime.ToString Format: yyyy-MM-dd, HH:mm:ss, ISO 8601, and More
Learn C# DateTime.ToString formats for yyyy-MM-dd, yyyyMMdd, HH:mm:ss, ISO 8601, filenames, logs, and common mistakes such as mm vs MM and hh vs HH.
C# DateTime.ToString Format Cookbook
Copy-paste C# DateTime.ToString format examples for yyyy-MM-dd, ISO 8601, logs, filenames, UTC, and localized output.
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: Add, Update, TryGetValue, TryAdd, and Iterate
Learn how to add, update, find, and iterate a C# Dictionary. Compare Add, indexer assignment, TryAdd, TryGetValue, and ContainsKey with practical examples.
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.GetValues: Declare, Iterate, Flags, and Convert to String
Learn C# enums with Enum.GetValues, declaration, iteration, Flags, conversion to string, parsing, and practical examples of named integer constants.
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.Empty Explained — Empty, Default, and New Guid()
Understand when to use Guid.Empty, default(Guid), and new Guid() in C# and how they compare in guard clauses and nullable code.
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.
C# GUID Parse and Format Reference
Learn how to parse GUIDs with Guid.Parse and Guid.TryParse, format them with N, D, B, P, and X, and normalize values for storage or display.
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#
Understand when IEnumerable<T> should be used for in-memory queries and when IQueryable<T> is better for database-backed LINQ.
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# Interface: Define, Implement, and Compare with an Abstract Class
Learn what a C# interface is, how to define and implement one, implement multiple interfaces, use explicit members, and choose an interface or abstract class.
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.
C# string.Join: Join Arrays, Lists, and Strings with a Separator
Learn how to use string.Join in C# to combine arrays, lists, and IEnumerable values with a separator, including commas, spaces, and custom delimiters.
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#.
C# Pattern Matching: is, switch, Property, and List Patterns
Learn C# pattern matching with is expressions, switch expressions, type patterns, property patterns, relational patterns, and list patterns.
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.
C# Random.Shared.Next: Generate Random Numbers and Ranges
Generate random integers in C# with Random.Shared.Next, Random.Next, and NextInt64. Learn ranges, repeatability, and when to use RandomNumberGenerator.
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 vs Class: Equality, Immutability, Constructors, and with
Learn the difference between a C# record and class, including value equality, immutability, constructors, with expressions, inheritance, and record struct examples.
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 Tester and Examples: Match, Groups, Replace, and Validate
Test and use C# regular expressions with examples for IsMatch, Match, Groups, named captures, Replace, validation, and common regex patterns.
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.
C# string[] vs List<string>: Differences, Performance, and Examples
Compare string[] and List<string> in C# for fixed-size versus dynamic collections, performance, Add and Remove operations, and conversion examples.
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.
C# String.Format: Format Specifiers, Numbers, Dates, and Padding
Learn C# string.Format with format specifiers for numbers, dates, currency, percentages, alignment, and zero-padding, plus examples compared with interpolation.
How to Use String Interpolation in C#
Use the $ prefix in C# for string interpolation to embed expressions in string literals. It is more readable than string.Format and supports format specifiers.
C# String Methods: Contains, Split, Replace, Trim, Join, and More
Learn the most commonly used C# string methods, including Contains, StartsWith, Split, Replace, Trim, Substring, IndexOf, Join, and padding 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.
Write Special Characters to a File in C#
Write raw text containing < > & " ' to a file in C# and learn when escaping is needed.
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 writing special characters and appending files.