How to design a Priority Queue in C#

What is a Priority Queue? To be a bit formal, a priority queue is an abstract data type (ADT), similar to a regular queue, but where each element has a priority associated to it. An element with high priority is served before an element with a low priority. Elements which have the same priority are […]

C# struct and class – when to use each?

Value types and Reference types In C# you have both Value types and Reference types. There are some fundamental differences between them that are important to understand. The most common value types are the simple ones, like int, bool, char, and long. But also enum and struct are value types. They are called value types […]

C# Protecting private collections from modification – Part 2

The common object issue In the last part I wrote about how you can protect a class’s private collections from modification by wrapping them in a ReadOnlyCollection before exposing them. But how about collections that are handed to your class? Consider the following code: What happens here is that MyClass takes a variable of reference […]

C# Protecting private collections from modification

Why do we want to hide data? One of the big advantages of object oriented programming is claimed to be possibilities to encapsulate data and hide internal implementation details. This enables us to make changes to our implementation without impacting our users and ensures our internal data does not get modified in ways that we […]

C# Pitfalls of returning IEnumerable

Generic and specific return types It is often preferred to work with as generic types as possible. Doing that opens up for more flexibility and being able to modify parts of the code without effecting any other parts. One example of this is IEnumerable<T> which is implemented by several generic collection types, such as HashSet<T>, […]

Building strings in C# with good performance

A little bit on strings Strings in C# are immutable. What that means is that you cannot modify an existing string, you must create a new one. Also strings are objects – sequential read only collections of char objects – so they are allocated on the managed heap, and therefore managed by the Garbage Collector […]

C# Collections – Non-generic or Generic?

Non-generic- vs generic collections When coding in C# you will pretty soon encounter Collections (Lists, Queues, Stacks, and so on). As soon as you wish to use a Collection of some sort you will have the choice of using one from the System.Collections namespace or one from the System.Collections.Generic namespace. The most commonly used Collection […]