100 C# Code Snippets for Everyday Problems

100 C# Code Snippets for Everyday Problems
May 8, 2023
22 minutes read

Welcome to this comprehensive compilation of 100 C# code snippets designed to tackle everyday problems! This article is inspired by Jeremy Grifski’s original work, “100 Python code snippets for everyday problems“- As developers, we often seek practical solutions to common challenges, and C# provides a powerful and versatile platform for addressing these issues.

In this article, we’ve curated a collection of C# code snippets that cover a wide range of scenarios you might encounter during software development. These snippets not only showcase the capabilities of C# but also serve as a valuable resource for enhancing your programming toolkit. So, whether you’re a seasoned developer or a newcomer to C#, dive in and explore these handy solutions!

Please note that this article’s inspiration, the Python version, was masterfully crafted by Jeremy Grifski, and you can find his insightful work “100 Python code snippets for everyday problems“. Happy coding!

Dictionaries (9 Snippets)

In C#, dictionaries serve as a robust and flexible data structure for connecting pairs of elements. Consider using a dictionary to tally the frequency of words present in this text.

The dictionary’s keys would represent distinct words found in this text, with each word linked to its respective count. This type of structure proves highly beneficial in numerous scenarios. Now, let’s delve into a few prevalent dictionary operations in C#!

Merging Two Dictionaries

Combining two dictionaries is a common operation when working with data structures in C#. However, merging dictionaries can be tricky, especially when there are duplicate keys. Here are some solutions to handle these cases:

Loading code snippet...

Inverting a Dictionary

Is there a scenario where you might consider swapping the keys and values of a dictionary? This operation can be complicated, especially when dealing with non-unique values or non-hashable values. Here are some solutions for simple cases:

Loading code snippet...

Performing a Reverse Dictionary Lookup

In some cases, you might want to perform a reverse lookup in a dictionary, meaning, you want to find a key based on a given value. This can be useful when the dictionary is too large to be inverted. Here are some ways to achieve this:

Loading code snippet...

The above snippets demonstrate different ways to perform a reverse dictionary lookup in C#. Depending on the size of the dictionary and the desired output, you can choose the most appropriate method for your use case.

Input/Output (4 Snippets)

Frequent instances of I/O involve interactions with databases, files, and command-line interfaces. While C# effectively simplifies I/O operations, certain complexities remain. Let’s examine a few of these challenges!

Writing to the Same Line

Sometimes you just need to write to the same line in your C# console application. The Console.Write method allows you to do this without adding a newline at the end of your string:

Loading code snippet...

Creating a C# Script Shortcut

Is there a way to conveniently execute a script with just a click of a button after developing it? Luckily, various methods enable you to achieve this.

One approach is to generate a batch file containing the subsequent code:

Loading code snippet...

Checking if a File Exists

Luckily in C# it’s easy. The System.IO namespace provides a set of methods for working with files, such as checking if a file exists:

Loading code snippet...

Parsing a CSV File

C# offers intriguing applications in the realm of data manipulation, which often requires dealing with substantial amounts of raw data in diverse formats, such as text files and CSV files.

Fortunately, C# comes equipped with numerous built-in tools for handling various file formats. For instance, parsing a CSV file can be accomplished effortlessly:

Loading code snippet...

Lists (27 Snippets)

Among various data structures, lists stand out as the most prevalent. In C#, a list represents a dynamic array that utilizes zero-based indexing. This means we can add and remove items without concerning ourselves with the underlying implementation, making lists highly intuitive.

Naturally, like other data structures mentioned here, lists present their own set of challenges. Let’s explore further!

Appending an Element to a List

As my interest in this collection grew, I became intrigued by the basics of C#. In other words, what tasks might beginners want to perform, and how many alternative approaches exist for accomplishing them? One such task is appending an element to a list.

C# offers numerous methods for adding items to lists. For instance, the widely-used Add() method is available. However, there are plenty of other options as well. Here are five:

Loading code snippet...

Retrieving the Last Item of a List

As we delve into lists, let’s discuss acquiring the final element of a list. In numerous languages, this typically requires a complex mathematical expression related to the list’s length. Would you believe that C# offers several more intriguing alternatives?

Loading code snippet...

Checking if a List Is Empty

For those with a background in statically typed languages such as Java or C++, the absence of static types in C# might seem unsettling. Indeed, not being aware of a variable’s type can be challenging at times; however, it also offers certain advantages

For example, C#’s type flexibility allows us to verify whether a list is empty through various techniques:

Loading code snippet...

Cloning a List

A fascinating aspect of programming for me is duplicating data types. In the context of the reference-based environment that we inhabit, it’s rarely a simple task, and this holds true for C# too.

Fortunately, when it comes to replicating a list, there are several methods available:

Loading code snippet...

Writing a List Comprehension

List comprehensions are a powerful feature in Python, but C# doesn’t have a direct equivalent. However, we can achieve similar functionality using LINQ (Language Integrated Query) in C#. LINQ is a powerful querying syntax that provides a concise and expressive way to work with collections. Here are some examples using LINQ:

Loading code snippet...

Summing Elements of Two Lists

Imagine having two lists, and your goal is to combine them into one list by merging their elements pairwise. In other words, you aim to add the first element of the first list to the first element of the second list and save the outcome in a new list. C# offers several methods to achieve this:

Loading code snippet...

Converting Two Lists Into a Dictionary

You might want to create a dictionary by mapping one list onto the other. Here’s how you can do that using LINQ in C#:

Loading code snippet...

Sorting a List of Strings

Sorting strings can be a bit more complicated than sorting numbers, but fortunately, C# provides several options for sorting strings:

Loading code snippet...

Sorting a List of Dictionaries

You most likely want to organize a list of dictionaries in some order, right? Here’s how you can sort a list of dictionaries in C# using LINQ:

Loading code snippet...

These examples demonstrate some common use cases for collections in C#. Using these code snippets, you’ll be able to tackle everyday programming challenges more efficiently.

Meta (5 Snippets)

It has been said that programming is about understanding code rather than writing it. In this case here are some tests for exactly that. Take a look at it:

Commenting Code

Comments are important in the code. Many times it has happened to read a code without comments from a couple of months ago and not understand where it comes from, what it does or why it is there. For that reason here are the options to make comments in C#:

Loading code snippet...

Testing Performance

Sometimes you want to compare the performance of different code snippets. C# provides a few straightforward options, including the Stopwatch class and the BenchmarkDotNet library. Take a look:

Loading code snippet...

Strings (14 Snippets)

They are commonly utilized for storing and manipulating text data such as names, email addresses, and more. Due to their importance, there are numerous string-related problems that developers often encounter. In this section, we will explore a few of those problems in the context of C#.

Comparing Strings

When working with strings, what I usually ask is: Is there any way to be able to compare them without much complexity?

Or if we go deeper: Do we need to know the alphabetical order? If the two strings are different? Or what?

There are different tools we can use for each scenario. Here’s a quick list of options:

Loading code snippet...

Here you can see some options. For instance, we can check for equality using the == operator. If we only need to check alphabetical ordering, we can use the CompareTo() method. Likewise, C# has the ReferenceEquals() method for checking reference equality.

Checking for Substrings

A common task when working with strings is determining if a string contains a specific substring. In C#, there are a few ways to solve this problem:

Loading code snippet...

Formatting a String

Oftentimes, we need to format strings to display information in a more readable or structured manner. Here are some options:

Loading code snippet...

Feel free to use any of these methods wherever you need them.

Converting a String to Lowercase

When formatting or comparing strings, sometimes it’s useful to convert all characters to lowercase. This can be helpful when checking for equality between two strings while ignoring casing differences. Here are a few ways to do that:

Loading code snippet...

Splitting a String by Whitespace

Handling language concepts such as words and sentences can be challenging. The way to divide a string into words that almost everyone will think of at first is with spaces. Here’s how to do that in C#:

Loading code snippet...

File Operations (10 Snippets)

File operations are a common requirement in many programming tasks. In this section, we will explore how to work with files and directories in C# using the System.IO namespace.

Reading a Text File

To read a text file in C#, you can use the File class and its ReadAllText() method:

Loading code snippet...

Writing a Text File

To write a text file in C#, you can use the File class and its WriteAllText() method:

Loading code snippet...

Appending Text to a File

To append text to an existing file in C#, you can use the File class and its AppendAllText() method:

Loading code snippet...

Reading a File Line by Line

To read a file line by line in C#, you can use the File class and its ReadLines() method:

Loading code snippet...

Creating a Directory

To create a directory in C#, you can use the Directory class and its CreateDirectory() method:

Loading code snippet...

Deleting a Directory

To delete a directory in C#, you can use the Directory class and its Delete() method:

Loading code snippet...

Checking if a File or Directory Exists

To check if a file or directory exists in C#, you can use the File and Directory classes with their respective Exists() methods:

Loading code snippet...

Getting Files in a Directory

To get a list of files in a directory in C#, you can use the Directory class and its GetFiles() method:

Loading code snippet...

Copying a File

To copy a file in C#, you can use the File class and its Copy() method:

Loading code snippet...

Moving a File

To move a file in C#, you can use the File class and its Move() method:

Loading code snippet...

Exception Handling (3 Snippets)

Handling exceptions is an essential part of writing robust and maintainable code. In this section, we will explore a few common ways to handle exceptions in C#.

Basic Try-Catch Block

To handle exceptions using a try-catch block in C#:

Loading code snippet...

Catching Specific Exceptions

To catch specific exceptions in C#, you can use multiple catch blocks:

Loading code snippet...

Using Finally Block

To execute code regardless of whether an exception was thrown or not, you can use the finally block in C#:

Loading code snippet...

LINQ (10 Snippets)

Language Integrated Query (LINQ) is a powerful feature in C# for querying and manipulating data. In this section, we will explore some common LINQ operations using the System.Linq namespace.

Filtering a Collection

To filter a collection using LINQ, you can use the Where() method:

Loading code snippet...

Selecting a Property from a Collection

To select a specific property from a collection using LINQ, you can use the Select() method:

Loading code snippet...

Sorting a Collection

To sort a collection using LINQ, you can use the OrderBy() method:

Loading code snippet...

Grouping a Collection

To group a collection using LINQ, you can use the GroupBy() method:

Loading code snippet...

Joining Collections

To join two collections using LINQ, you can use the Join() method:

Loading code snippet...

Taking the First n Elements

To take the first n elements from a collection using LINQ, you can use the Take() method:

Loading code snippet...

Skipping the First n Elements

To skip the first n elements from a collection using LINQ, you can use the Skip() method:

Loading code snippet...

Checking if an Element Exists

To check if an element exists in a collection using LINQ, you can use the Any() method:

Loading code snippet...

Counting Elements

To count the number of elements in a collection using LINQ, you can use the Count() method:

Loading code snippet...

Aggregating Elements

To aggregate elements in a collection using LINQ, you can use the Aggregate() method:

Loading code snippet...

Threading (9 Snippets)

Threading is an important aspect of concurrent programming in C#. In this section, we will explore how to work with threads using the System.Threading namespace.

Creating a New Thread

To create a new thread in C#, you can use the Thread class:

Loading code snippet...

Starting a Thread

To start a thread in C#, you can use the Start() method:

Loading code snippet...

Joining a Thread

To wait for a thread to finish executing in C#, you can use the Join() method:

Loading code snippet...

Thread Sleep

To pause the current thread for a specified time in C#, you can use the Sleep() method:

Loading code snippet...

Using Thread Pools

To use a thread pool in C#, you can use the ThreadPool class:

Loading code snippet...

Using Tasks

To create and run a task in C#, you can use the Task class:

Loading code snippet...

Waiting for Tasks

To wait for a task to complete in C#, you can use the Wait() method:

Loading code snippet...

Cancelling a Task

To cancel a task in C#, you can use the CancellationTokenSource class:

Loading code snippet...

Handling Task Exceptions

To handle exceptions in a task, you can use a try-catch block inside the task:

Loading code snippet...

You May Also Like

Mastering Background Services in .NET Core

Mastering Background Services in .NET Core

Background services in .NET Core provide a powerful mechanis...

Caching in .NET Full Guide

Caching in .NET Full Guide

In this article, we will delve into the fascinating world of...

Leave a reply

Loading comment form...