C# code snippets with use cases
29 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test of whether the SDK and project work.
- Variables and types β Store values and check their type.
- Date and time β Calculate deadlines, format timestamps.
- Enum β Represent fixed sets of choices in a type-safe way (weekdays, statuses, roles).
Control flow
- if / else if / else β React differently depending on the situation, e.g. calculate grades or price tiers.
- for and foreach loops β Process every element of a list or repeat n times.
- switch expression with patterns β Write branches by type or value range compactly (price tiers, shapes, status codes).
Data structures
- Working with lists (List<T> & LINQ) β Manage collections of values: add, sort, filter.
- Dictionary β Store mappings, e.g. configurations or intermediate results.
- Sort by multiple criteria β Order records, e.g. users by city and then by age.
- Group and sum β Analyze revenue per customer or category.
Strings
- Count words β Text analysis, e.g. the most frequent words in a document.
- Regular expression β Find email addresses, phone numbers or patterns in text.
- Manipulate strings β Clean up input, split and assemble text.
Advanced
- Iterator with yield return β Produce large or infinite sequences piece by piece without holding everything in memory.
- Extension method β Add your own helper methods to existing types without modifying them.
- Event publisher and subscriber β Decouple components: one object reports changes, others react (UI, loggingβ¦
- Generic class and constraint β Write reusable containers or repositories for different types.
- using and IDisposable β Reliably release files, database connections and locks.
More snippets
- Method with default value β Bundle recurring logic, e.g. greeting texts or calculations.
- Class with inheritance β Bundle data and behavior, e.g. users, products, game characters.
- Record with with-expression β Copy immutable data objects and change individual fields (DTOs, configurations).
- try / catch / finally β Guard user input or network access without the program crashing.
- Handle null safely β Process optional values (search results, missing fields) without a NullReferenceException.
- Read and write a file β Save and load logs, configurations or text data.
- Read and write JSON β Exchange data with web APIs or other programs, save configurations.
- HTTP request (HttpClient) β Fetch data from a web API.
- Run tasks in parallel with Task.WhenAll β Complete several slow I/O tasks (API calls, downloads) at the same time.
- Command-line arguments β Build your own CLI tools with parameters.