C# – ‘internal’ vs ‘protected’

The public/private access modifiers are straightforward: public means everything has access while private means only the class has access. The internal/protected access modifiers are a little more complicated. In other words, internal means it’s “private” to the assembly and protected means it’s “private” to the class and its subclasses. To illustrate the difference, I’ll show … Read more

C# – Default access modifiers

Classes (and other types) are internal by default. Class members (methods/properties/fields) are private by default. These defaults are applied when you don’t explicitly declare an access modifier. Here’s an example: Since the access modifiers aren’t declared, it uses the defaults. The class is internal while all of the members are private. This is almost never … Read more

C# – Get int value from enum

The simplest way to get an enum’s int value is by casting it to an int. Here’s an example: This outputs the following: When the enum is generic (of type ‘Enum’) You can’t cast a generic ‘Enum’ to int, otherwise you get a compiler error (CS0030 Cannot convert type ‘System.Enum’ to ‘int’). Use Convert.Int32() instead. … Read more

C# – How to convert string to int

There are three ways to convert a string to an int: I’ll show examples of using these approaches. Use int.Parse() int.Parse() takes a string and converts it to a 32-bit integer. Here’s an example of using int.Parse(): When conversion fails int.Parse() throws an exception if it can’t convert the string to an int. There are … Read more

C# – How to convert char to int

Converting a char to an int means getting the numeric value that the char represents (i.e. ‘1’ to 1). This is not the same as casting the char to an int, which gives you the char’s underlying value (i.e. ‘1’ is 49). There are three ways to convert a char to an int: I’ll show … Read more

C# – Using String.Join()

You can use String.Join() to convert a collection of items to a string with a separator (such as a comma). Here’s an example of using String.Join() to convert a List of strings to a comma-separated string: This results in the following comma-separated string: String.Join() can be used on wide variety of input: I’ll show a … Read more

C# – Convert a List to a string

There are two good ways to convert a List<T> to a string: I’ll show examples of both approaches. Using String.Join() String.Join() is the simplest way to convert a List to a string. With this method, you pass in the List and a delimiter and it outputs a string. You can use any delimiter you want. … Read more

C# – Delete all files in a directory

Use Directory.EnumerateFiles() to get the file paths in a directory. Then loop over the file paths and delete each file. Here’s an example: This deletes the root directory’s files without deleting the directory itself. I’ll show more examples. Delete all files with a specific extension Use Directory.EnumerateFiles’ searchPattern pattern to search for files with a … Read more

C# – How to use LinkedList

LinkedList<T> is a doubly linked list. It consists of nodes with values (i.e. integers, strings, etc…) and links to the next and previous node. LinkedList<T> has a reference to the head and tail nodes, which enables efficient insertion (and removal) from the start and end of the list. The main reason to use LinkedList<T> is … Read more

C# – Remove duplicates from a list

The simplest (and most efficient) way to remove duplicates from a list is by iterating, keeping track of items you’ve seen with a HashSet, and discarding items you’ve already seen. I’ll show four ways to implement this O(n) algorithm. At the end, I’ll explain a few inefficient approaches to avoid. Remove duplicates with ToHashSet() and … Read more

C# – Remove items from a list while iterating

There are two ways to iterate through a List<T> and remove items based on a condition: These remove items from the list in an in-place manner (i.e. modify the original list) and avoid the problems you run into when doing this incorrectly (such as using a foreach or looping forward). I’ll show examples below. Then … Read more

C# – Remove items from a list

Here are the different ways to remove items from a list: I’ll show examples of using these methods. Remove item by index with List.RemoveAt() You can use List.RemoveAt() to remove an item at an index (0-based). Here’s an example of removing the first and last item from the list: This removes the first item “A” … Read more

C# – How to add to a list

There are four ways to add items to a list: I’ll show examples of all of these methods for adding to a list. Append items with List.Add() You can use List.Add() to append an item to the end of the list. Here’s an example: This outputs the list’s contents: Initialize a list with items You … Read more

C# – Convert DateTime to string

When you want to convert a DateTime to a string, use ToString(). By default, this converts the DateTime to a string using the current culture’s date/time format (from the OS). In most cases, you’ll want to specify the format to use. You can do this by passing in a format string consisting of format specifier … Read more

OverflowException: Value was either too large or too small for an int32

Problem When you try to convert a string to an integer with int.Parse() (or Convert.ToInt32()), you get the following exception: System.OverflowException: Value was either too large or too small for an Int32. The problem is the integer value in the string can’t fit in the 32-bit integer. Int32 (int) can only hold values between -2147483648 … Read more

C# – Convert an array to a list

The simplest way to convert an array to a list is with the ToList() Linq method: This outputs the following: The List<T> class stores data in a dynamically sized array. So converting an array to a list boils down to copying the array to the list’s internal array. That’s what ToList() does. It creates a … Read more

C# – Convert list to array

The simplest way to convert a list to an array is to use the List.ToArray() method: This outputs the following: Internally, the List<T> class stores elements in a dynamically sized array (it resizes when necessary). So under the hood, List.ToArray() uses Array.Copy() to copy the list’s internal array to a new array. This is very … Read more

C# – How to sort a list

When you need to sort a list, you don’t need to reinvent the wheel. You can use one of these three built-in methods for sorting a list: In this article, I’ll show examples of using these three approaches for sorting a list. Sort a list with OrderBy() (Linq) The OrderBy() Linq method generates an IOrderedEnumerable … Read more

C# – Using a list of tuples

Here’s an example of how to initialize a list of named tuples: This creates a list of named value tuples (ValueTuple<string, int>) using list initializer syntax and then loops through the tuples. I suggest always using named value tuples (not System.Tuple). This outputs the following: I’ll now show how to add to the list of … Read more

C# – How to sort a dictionary

Dictionaries are unordered data structures. Key/value pairs aren’t stored in sorted order. When you want the Dictionary in sorted order, there are two simple options: I’ll show both options. Sort Dictionary with OrderBy() Use OrderBy() (from System.Linq) to sort the Dictionary by key or value. It returns the Dictionary’s KeyValuePairs in ascending sorted order. I’ll … Read more

C# – How to deconstruct tuples

Deconstructing a tuple means assigning its fields to several variables at once by using the deconstruction assignment syntax. This is also referred to as destructuring or tuple unpacking. Here’s an example of deconstructing a tuple into two variables: This outputs: Deconstructing the tuple assigns the fields (Item1 and Item2) to variables based on position. The … Read more

C# – How to use named tuples

You can use tuples to contain multiple values and pass them around. By default, the tuple field names are unfriendly – Item1, Item2, etc… Instead of using these default names, you can name the tuple fields. Here’s an example of creating and using a named tuple: Meaningful names makes tuples easier to use. movieTuple.title is … Read more

SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects

When you try to execute a query with EF Core that has parameters, you get the following exception: System.InvalidCastException: The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects The error message is confusing because it’s not showing the full type names. This error means you’re using System.Data.SqlClient.SqlParameter, but EF Core only accepts Microsoft.Data.SqlClient.SqlParameter. … Read more