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!
C# Code Snippets: 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:
Dictionary<string, string> dict1 = new Dictionary<string, string> { { "Superman", "Flight" } };
Dictionary<string, string> dict2 = new Dictionary<string, string> { { "Batman", "Gadgets" } };
// Using LINQ
var merged = dict1.Concat(dict2).ToDictionary(x => x.Key, x => x.Value);
// Using a foreach loop
foreach (var item in dict2)
{
dict1[item.Key] = item.Value;
}
// Using the Union extension method
var merged2 = dict1.Union(dict2).ToDictionary(x => x.Key, x => x.Value);
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:
Dictionary<string, string> heroesAbilities = new Dictionary<string, string>
{
{ "Flash", "Super Speed" },
{ "Green Lantern", "Power Ring" },
{ "Aquaman", "Atlantean Strength" }
};
// Inverting the dictionary using LINQ
var inverted = heroesAbilities.ToDictionary(x => x.Value, x => x.Key);
// Inverting the dictionary using a foreach loop
Dictionary<string, string> inverted2 = new Dictionary<string, string>();
foreach (var item in heroesAbilities)
{
inverted2[item.Value] = item.Key;
}
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:
Dictionary<string, int> dimensions = new Dictionary<string, int>
{
{ "length", 10 },
{ "width", 20 },
{ "height", 30 }
};
int valueToFind = 20;
// Brute force solution -- single key
foreach (var item in dimensions)
{
if (item.Value == valueToFind)
{
Console.WriteLine($"{item.Key}: {item.Value}");
break;
}
}
// Brute force solution -- multiple keys
foreach (var item in dimensions)
{
if (item.Value == valueToFind)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
// Using LINQ -- single key
var key = dimensions.FirstOrDefault(x => x.Value == valueToFind).Key;
Console.WriteLine($"{key}: {valueToFind}");
// Using LINQ -- multiple keys
var keys = dimensions.Where(x => x.Value == valueToFind).Select(x => x.Key);
foreach (var k in keys)
{
Console.WriteLine($"{k}: {valueToFind}");
}
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:
Console.Write("The Office");
Console.Write(" Parks and Recreation");
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:
@echo off
csc /path/to/MyProgram.cs
MyProgram.exe
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:
using System.IO;
// Check if file exists using File.Exists method
bool exists = File.Exists("/path/to/file");
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:
using System;
using System.IO;
// Read all lines from the CSV file
string[] lines = File.ReadAllLines("/path/to/data.csv");
// Process each line
foreach (string line in lines)
{
// Split the line into fields
string[] fields = line.Split(',');
// Do something with the fields, e.g., print them
Console.WriteLine($"{fields[0]} - {fields[1]} - {fields[2]}");
}
Lists (27 Snippets)
Among various data structures, lists stand out as the most prevalent. In C# code snippet, 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:
// Statically defined list
List<int> myList = new List<int> {2, 5, 6};
// Appending using Add()
myList.Add(5); // [2, 5, 6, 5]
// Appending using AddRange()
myList.AddRange(new List<int> {9}); // [2, 5, 6, 5, 9]
// Appending using Insert()
myList.Insert(myList.Count, -4); // [2, 5, 6, 5, 9, -4]
// Appending using InsertRange()
myList.InsertRange(myList.Count, new List<int> {3}); // [2, 5, 6, 5, 9, -4, 3]
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?
List<string> myList = new List<string> {"red", "blue", "green"};
// Get the last item with brute force using Count
string lastItem = myList[myList.Count - 1];
// Remove the last item from the list using RemoveAt
myList.RemoveAt(myList.Count - 1);
// Get the last item using Linq Last() method
lastItem = myList.Last();
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:
List<int> myList = new List<int>();
// Check if a list is empty by its Count
if (myList.Count == 0)
{
// the list is empty
}
// Check if a list is empty by its type flexibility **preferred method**
if (!myList.Any())
{
// the list is empty
}
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:
List<int> myList = new List<int> {27, 13, -11, 60, 39, 15};
// Clone a list by brute force
List<int> myDuplicateList = myList.Select(item => item).ToList();
// Clone a list with the List constructor
myDuplicateList = new List<int>(myList);
// Clone a list with the ToList() Linq extension method
myDuplicateList = myList.ToList(); // preferred method
// Clone a list with the DeepCopy method (requires custom implementation)
myDuplicateList = DeepCopy(myList);
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:
var myList = new List<int> { 2, 5, -4, 6 };
// Duplicate a 1D list of constants
var duplicatedList = myList.Select(item => item).ToList();
// Duplicate and scale a 1D list of constants
var scaledList = myList.Select(item => 2 * item).ToList();
// Duplicate and filter out non-negatives from 1D list of constants
var filteredList = myList.Where(item => item < 0).ToList();
// Duplicate, filter, and scale a 1D list of constants
var filteredAndScaledList = myList.Where(item => item < 0).Select(item => 2 * item).ToList();
// Generate all possible pairs from two lists
var list1 = new List<int> { 1, 3, 5 };
var list2 = new List<int> { 2, 4, 6 };
var pairsList = list1.SelectMany(a => list2, (a, b) => (a, b)).ToList();
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:
var ethernetDevices = new List<int> { 1, 7, 2, 8374163, 84302738 };
var usbDevices = new List<int> { 1, 7, 1, 2314567, 0 };
// Using LINQ's Zip method
var allDevices = ethernetDevices.Zip(usbDevices, (x, y) => x + y).ToList();
// Using a for loop
var allDevicesForLoop = new List<int>();
for (int i = 0; i < ethernetDevices.Count; i++)
{
allDevicesForLoop.Add(ethernetDevices[i] + usbDevices[i]);
}
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#:
var columnNames = new List<string> { "id", "color", "style" };
var columnValues = new List<object> { 1, "red", "bold" };
// Convert two lists into a dictionary with LINQ
var nameToValueDict = columnNames.Zip(columnValues, (key, value) => new { key, value }).ToDictionary(x => x.key, x => x.value);
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:
var myList = new List<string> { "leaf", "cherry", "fish" };
// Using the Sort method
myList.Sort();
// Using the Sort method with StringComparison.OrdinalIgnoreCase for case-insensitive sorting
myList.Sort(StringComparer.OrdinalIgnoreCase);
// Using the OrderBy method with LINQ
var sortedList = myList.OrderBy(x => x).ToList();
// Using the OrderBy method with LINQ for case-insensitive sorting
var sortedIgnoreCaseList = myList.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList();
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:
var csvMappingList = new List<Dictionary<string, object>>
{
new Dictionary<string, object> { { "Name", "Johnny" }, { "Age", 23 }, { "Favorite Color", "Blue" } },
new Dictionary<string, object> { { "Name", "Ally" }, { "Age", 41 }, { "Favorite Color", "Magenta" } },
new Dictionary<string, object> { { "Name", "Jasmine" }, { "Age", 29 }, { "Favorite Color", "Aqua" } }
};
// Sort by Age using LINQ's OrderBy method
var sortedList = csvMappingList.OrderBy(dict => (int)dict["Age"]).ToList();
These c# code snippet 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#:
// Here is an inline comment in C#
/* Here
is
a
multiline
comment
in
C#
*/
/// <summary>
/// Here is an XML documentation comment in C#.
/// This is often used to provide additional information
/// about the code and is displayed by IntelliSense.
/// </summary>
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:
// Stopwatch solution
using System;
using System.Diagnostics;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// example snippet
var result = new List<(int, int)>();
foreach (int a in new[] { 1, 3, 5 })
{
foreach (int b in new[] { 2, 4, 6 })
{
result.Add((a, b));
}
}
stopwatch.Stop();
Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}");
// BenchmarkDotNet solution
// Install the BenchmarkDotNet NuGet package to use this solution
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class MyBenchmark
{
[Benchmark]
public List<(int, int)> TestSnippet()
{
var result = new List<(int, int)>();
foreach (int a in new[] { 1, 3, 5 })
{
foreach (int b in new[] { 2, 4, 6 })
{
result.Add((a, b));
}
}
return result;
}
}
public class Program
{
public static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<MyBenchmark>();
}
}
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:
string player1 = "Crosby";
string player2 = "Malkin";
string player3 = "Guentzel";
// Brute force comparison (equality only)
bool isSamePlayer = player1.Length == player3.Length;
if (isSamePlayer)
{
for (int i = 0; i < player1.Length; i++)
{
if (player1[i] != player3[i])
{
isSamePlayer = false;
break;
}
}
}
// Direct comparison
bool isEqual = player1 == player3; // False
bool isGreater = player1.CompareTo(player3) > 0; // False
bool isLessOrEqual = player2.CompareTo(player2) <= 0; // True
// Reference checking
bool isSameReference = ReferenceEquals(player1, player1); // True
bool isDifferentReference = ReferenceEquals(player2, player1); // False
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:
string[] addresses = {
"123 Elm Street",
"531 Oak Street",
"678 Maple Street"
};
string street = "Elm Street";
// Brute force (not recommended)
foreach (string address in addresses)
{
int addressLength = address.Length;
int streetLength = street.Length;
for (int index = 0; index <= addressLength - streetLength; index++)
{
string substring = address.Substring(index, streetLength);
if (substring == street)
{
Console.WriteLine(address);
}
}
}
// The IndexOf() method
foreach (string address in addresses)
{
if (address.IndexOf(street) >= 0)
{
Console.WriteLine(address);
}
}
// The Contains() method (preferred)
foreach (string address in addresses)
{
if (address.Contains(street))
{
Console.WriteLine(address);
}
}
Formatting a String
Oftentimes, we need to format strings to display information in a more readable or structured manner. Here are some options:
string name = "John";
int age = 25;
// String formatting using concatenation
Console.WriteLine("My name is " + name + ", and I am " + age + " years old.");
// String formatting using composite formatting
Console.WriteLine("My name is {0}, and I am {1} years old.", name, age);
// String formatting using interpolation (C# 6.0+)
Console.WriteLine($"My name is {name}, and I am {age} years old");
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:
string hero = "All Might";
// Using ToLower() method
string output = hero.ToLower();
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#:
string myString = "Hi, fam!";
// Using the built-in Split() method
string[] words = myString.Split();
foreach (string word in words)
{
Console.WriteLine(word);
}
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:
using System.IO;
string filePath = "example.txt";
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);
Writing a Text File
To write a text file in C#, you can use the File
class and its WriteAllText()
method:
using System.IO;
string filePath = "output.txt";
string content = "Hello, World!";
File.WriteAllText(filePath, content);
Appending Text to a File
To append text to an existing file in C#, you can use the File
class and its AppendAllText()
method:
using System.IO;
string filePath = "log.txt";
string logEntry = "New log entry";
File.AppendAllText(filePath, logEntry);
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:
using System.IO;
string filePath = "example.txt";
foreach (string line in File.ReadLines(filePath))
{
Console.WriteLine(line);
}
Creating a Directory
To create a directory in C#, you can use the Directory
class and its CreateDirectory()
method:
using System.IO;
string directoryPath = "new_directory";
Directory.CreateDirectory(directoryPath);
Deleting a Directory
To delete a directory in C#, you can use the Directory
class and its Delete()
method:
using System.IO;
string directoryPath = "old_directory";
Directory.Delete(directoryPath, true);
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:
using System.IO;
string filePath = "example.txt";
string directoryPath = "example_directory";
bool fileExists = File.Exists(filePath);
bool directoryExists = Directory.Exists(directoryPath);
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:
using System.IO;
string directoryPath = "example_directory";
string[] files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
Console.WriteLine(file);
}
Copying a File
To copy a file in C#, you can use the File
class and its Copy()
method:
using System.IO;
string sourceFile = "example.txt";
string destinationFile = "copy_example.txt";
File.Copy(sourceFile, destinationFile);
Moving a File
To move a file in C#, you can use the File
class and its Move()
method:
using System.IO;
string sourceFile = "example.txt";
string destinationFile = "moved_example.txt";
File.Move(sourceFile, destinationFile);
C# 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#:
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Catching Specific Exceptions
To catch specific exceptions with C# code snippets, you can use multiple catch blocks:
try
{
// Code that may throw different exceptions
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.FileName}");
}
catch (IOException ex)
{
Console.WriteLine($"I/O error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}
Using Finally Block
To execute code regardless of whether an exception was thrown or not, you can use the finally block in C#:
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
// Code that will always be executed
}
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:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
Selecting a Property from a Collection
To select a specific property from a collection using LINQ, you can use the Select()
method:
using System.Linq;
List<string> names = new List<string> { "John", "Jane", "Doe" };
List<int> nameLengths = names.Select(x => x.Length).ToList();
Sorting a Collection
To sort a collection using LINQ, you can use the OrderBy()
method:
using System.Linq;
List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };
List<int> sortedNumbers = numbers.OrderBy(x => x).ToList();
Grouping a Collection
To group a collection using LINQ, you can use the GroupBy()
method:
using System.Linq;
List<string> names = new List<string> { "John", "Jane", "Doe" };
var groups = names.GroupBy(x => x.Length);
foreach (var group in groups)
{
Console.WriteLine($"Names with {group.Key} characters:");
foreach (string name in group)
{
Console.WriteLine(name);
}
}
Joining Collections
To join two collections using LINQ, you can use the Join()
method:
using System.Linq;
List<string> names = new List<string> { "John", "Jane", "Doe" };
List<int> ages = new List<int> { 30, 25, 35 };
var nameAgePairs = names.Join(ages, name => names.IndexOf(name), age => ages.IndexOf(age), (name, age) => new { Name = name, Age = age });
foreach (var pair in nameAgePairs)
{
Console.WriteLine($"{pair.Name}: {pair.Age}");
}
Taking the First n Elements
To take the first n elements from a collection using LINQ, you can use the Take()
method:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> firstThreeNumbers = numbers.Take(3).ToList();
Skipping the First n Elements
To skip the first n elements from a collection using LINQ, you can use the Skip()
method:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> remainingNumbers = numbers.Skip(2).ToList();
Checking if an Element Exists
To check if an element exists in a collection using LINQ, you can use the Any()
method:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
bool hasEvenNumber = numbers.Any(x => x % 2 == 0);
Counting Elements
To count the number of elements in a collection using LINQ, you can use the Count()
method:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int evenNumberCount = numbers.Count(x => x % 2 == 0);
Aggregating Elements
To aggregate elements in a collection using LINQ, you can use the Aggregate()
method:
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = numbers.Aggregate((x, y) => x + y);
C# Code Snippets: 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:
using System.Threading;
void PrintNumbers()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
Thread newThread = new Thread(PrintNumbers);
Starting a Thread
To start a thread in C#, you can use the Start()
method:
newThread.Start();
Joining a Thread
To wait for a thread to finish executing in C#, you can use the Join()
method:
newThread.Join();
Thread Sleep
To pause the current thread for a specified time in C#, you can use the Sleep()
method:
Thread.Sleep(1000); // Sleep for 1 second
Using Thread Pools
To use a thread pool in C#, you can use the ThreadPool
class:
using System.Threading;
ThreadPool.QueueUserWorkItem(PrintNumbers);
Using Tasks
To create and run a task in C#, you can use the Task
class:
using System.Threading.Tasks;
Task.Run(PrintNumbers);
Waiting for Tasks
To wait for a task to complete with C# code snippets, you can use the Wait()
method:
Task task = Task.Run(PrintNumbers);
task.Wait();
Cancelling a Task
To cancel a task using a C# code snippet, you can use the CancellationTokenSource
class:
using System.Threading;
using System.Threading.Tasks;
CancellationTokenSource cts = new CancellationTokenSource();
Task.Run(() => PrintNumbers(cts.Token), cts.Token);
cts.Cancel();
Handling Task Exceptions
To handle exceptions in a task, you can use a try-catch block inside the task:
using System.Threading.Tasks;
Task.Run(() =>
{
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
});