Thread-safe bags in .NET

Bags are very similar to Stacks and Queues. We saw that both stacks and queues order their elements in a well defined way: last-in-first-out and first-in-first-out respectively. Bags on the other hand are unordered collections. There’s no guarantee on how, i.e. in which order the elements will be retrieved.

Unlike stacks and queues, bags have no one-to-one single-threaded implementation in .NET. They are however implemented as thread-safe ConcurrentBag objects in the System.Collections.Concurrent namespace.

Read more of this post

Thread safe queues in .NET

We saw how standard Queues work in .NET in this post. Queues are first-in-first-out collections where the first element added to the collection will the first to be removed. Queues are ideal to model consumer-producer scenarios where a producer adds items to a queue which are then processed by a consumer in the order they came in.

If you’d like to have a Queue that is shared among multiple threads in a multi-threaded application then the “normal” Queue of T object won’t be enough. You can never be sure of the current state of the queue in the very moment when a certain thread tries to dequeue an item from it. The queue may have been modified by another thread just a millisecond before and then the Dequeue method will fail. In general you should be very careful with how you share the resources among different threads.

Read more of this post

Thread-safe stacks in .NET

We saw how Stacks work in .NET in this post. Stacks are last-in-first-out collections where the last element added to the collection will the first to be removed.

If you’d like to have a Stack that is shared among multiple threads in a multi-threaded application then the “normal” Stack of T object won’t be enough. You can never be sure of the current state of the stack in the very moment when a certain thread tries to pop an item from it. The stack may have been modified by another thread just a millisecond before and then the Pop method will fail. In general you should be very careful with how you share the resources among different threads.

Read more of this post

FIFO collections with Queue of T in .NET C#

FIFO, that is first-in-first-out, collections are represented by the generic Queue of T class in .NET. Queues are collections where a new element is placed on top of the collection and is removed last when the items are retrieved.

Let’s say that you’re throwing a party where you follow a Queue policy as far as guests are concerned. As time goes by you’d like all of them to leave eventually and the first one to go will be the first person who has arrived. This is probably a most just policy than what we saw in the post on stack collections.

Read more of this post

Creating sorted sets with C# .NET

The SortedSet of T object is the sorted version of the HashSet object. We’ve already seen what a HashSet can do for you in the referenced post. A SortedSet keeps the elements in increasing order.

Consider the following integer set:

SortedSet<int> sortedInts = new SortedSet<int>();
sortedInts.Add(1);
sortedInts.Add(4);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(3);
sortedInts.Add(10);
sortedInts.Add(8);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(4);
foreach (int i in sortedInts)
{
	Debug.WriteLine(i);
}

This will print…

1
3
4
8
10

Notice that duplicates were rejected to ensure uniqueness just like in the case of HashSets.

That is straightforward for primitive types like integers since .NET “knows” how to compare them. It can decide whether 10 is greater than 5, we don’t need to provide any help.

However what about reference types like your own objects, such as this one?

public class Band
{
	public string Name { get; set; }
	public int YearFormed { get; set; }
	public int NumberOfMembers { get; set; }
	public int NumberOfRecords { get; set; }
}

How can .NET decide on the ordering of your objects? We’ll need to give it a hint by providing an object which implements the generic IComparer of T interface like we saw in this post. We’ll let the Band objects be sorted by their names:

public class BandNameComparer : IComparer<Band>
{
	public int Compare(Band x, Band y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

Let’s see this in action:

SortedSet<Band> bands = new SortedSet<Band>(new BandNameComparer());
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Well known band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });

foreach (Band band in bands)
{
	Debug.WriteLine(band.Name);
}

This will print…

Best band
Famous band
Great band
Well known band

…so not only were the items sorted by their names but the non-unique values were rejected as well. The IComparer argument also provided a way to declare equality.

View all various C# language feature related posts here.

LIFO collections with Stack of T in .NET C#

LIFO, that is last-in-first-out, collections are represented by the generic Stack of T class in .NET. Stacks are collections where a new element is placed on top of the collection and is removed first when an item is being retrieved. Hence the item that was entered first will get to stay longest in the stack.

Let’s say that you’re throwing a party where you follow a Stack policy as far as guests are concerned. As time goes by you’d like all of them to leave eventually and the first one to go will be the last person who has arrived. This might not be a very fair way to treat your guests but there you go.

Read more of this post

Using linked lists in .NET with C#

Linked lists are very efficient if you want to insert and remove items in a collection frequently. Linked lists do not store their elements in contiguous regions in memory, like e.g. the List of T object. Instead elements in linked lists can be stored anywhere.

The elements are linked by their “next” and “previous” references. The first element will have a “next” pointer to the element that comes after that. The second element in turn will have a reference to the previous and next elements. The first element will of course only have a reference to the “next” element and “previous” will be null, whereas the last element will point to the previous element and “next” will be null. All elements in between will have two references. Such a linked list is also called a doubly linked list.

One big difference between linked lists and “normal” lists is that linked lists have no index accessors. You just cannot extract the element #3 for example without looping through the linked list and stopping at the third element.

Read more of this post

Keeping the key-values sorted by using a SortedDictionary with C# .NET

You can use the generic SortedDictionary of Key and Value to automatically keep the key value items sorted by their keys. Any time you add a new key value pair the dictionary will reorder the items. The SortedDictionary was optimised for frequent changes to its list of items. Keep in mind that the items will be sorted by their key and not their value.

Consider the following simple custom object:

public class Student
{
	public string Name { get; set; }
	public string SchoolName { get; set; }
}

Let’s organise a couple of students into a sorted dictionary by their birthdates:

SortedDictionary<int, List<Student>> birthDates = new SortedDictionary<int, List<Student>>();
birthDates[1990] = new List<Student>()
{
	new Student()
	{
		Name = "John", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Diana", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Peter", 
		SchoolName ="Awesome school"
	}
};

birthDates[1979] = new List<Student>()
{
	new Student()
	{
		Name = "Daniel", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Hanna", 
		SchoolName ="Awesome school"
	}
};

birthDates[1985] = new List<Student>()
{
	new Student()
	{
		Name = "Daniel", 
		SchoolName ="Awesome school"
	},
	new Student()
	{
		Name = "Hanna", 
		SchoolName ="Great school"
	}
};

foreach (var kvp in birthDates)
{
	Debug.WriteLine(kvp.Key);
}

The code prints the years in ascending order:

1979
1985
1990

Remember though that this is a Dictionary so if you add another key-value with an existing key then the existing key will be overwritten.

This was a simple case as ordering – and uniqueness – is based on an integer key, i.e. the year of birth. .NET can order primitive types like integers in a natural way, we don’t have to give it any help. .NET can also compare primitive types, i.e. it can determine whether two integers or two strings are equal.

However, what if the key is a custom object? Say we’d like to have Student objects as keys and a list of strings as values. The list of strings can store the titles of the essays they have written at school. How will .NET be able to determine the ordering and uniqueness of Student? It cannot of course. We’ll have to declare how two student objects can be ordered and compared. Both can be achieved by overriding the generic IComparable of T interface like we saw in this post. Let’s order the Student objects by their Name properties:

public class StudentNameComparer : IComparer<Student>
{
	public int Compare(Student x, Student y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

The following example shows how you can supply the custom comparer to a sorted dictionary. I’ve ignored assigning school names and the list of essay titles, those are not relevant now:

SortedDictionary<Student, List<string>> essays = new SortedDictionary<Student, List<string>>(new StudentNameComparer());
essays.Add(new Student() { Name = "John" }, new List<string>());
essays.Add(new Student() { Name = "Adam" }, new List<string>());
essays.Add(new Student() { Name = "Paul" }, new List<string>());
essays.Add(new Student() { Name = "Hannah" }, new List<string>());
essays.Add(new Student() { Name = "Eve" }, new List<string>());
essays.Add(new Student() { Name = "Anne" }, new List<string>());
essays.Add(new Student() { Name = "Mary" }, new List<string>());

foreach (var kvp in essays)
{
	Debug.WriteLine(kvp.Key.Name);
}

This prints the names in the correct alphabetical order:

Adam
Anne
Eve
Hannah
John
Mary
Paul

View all various C# language feature related posts here.

Using the KeyedCollection object in C# .NET

The abstract generic KeyedCollection object can be used to declare which field of your custom object to use as a key in a Dictionary. It provides sort of a short-cut where you’d want to organise your objects in a Dictionary by an attribute of that object.

Let’s take the following object as an example:

public class CloudServer
{
	public string CloudProvider { get; set; }
	public string ImageId { get; set; }
	public string Size { get; set; }
}

The Image IDs are always unique so the ImageId property seems to be a good candidate for a dictionary key.

Here’s an example:

Read more of this post

Getting notified when collection changes with ObservableCollection in C# .NET

Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.

If you don’t know what events, event handlers and delegates mean then start here.

Let’s see a simple example with a collection of strings:

ObservableCollection<string> names = new ObservableCollection<string>();
names.Add("Adam");
names.Add("Eve");
names.Add("Clive");
names.Add("Anne");
names.Add("John");
names.Add("Peter");
names.Add("Hannah");

Nothing special so far I guess. This looks exactly like a “normal” collection.

The following example demonstrates the CollectionChanged event:

private static void RunObservableCollectionCode()
{
	ObservableCollection<string> names = new ObservableCollection<string>();
	names.CollectionChanged += names_CollectionChanged;
	names.Add("Adam");
	names.Add("Eve");
	names.Remove("Adam");
	names.Add("John");
	names.Add("Peter");
	names.Clear();
}

static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
	Debug.WriteLine("Change type: " + e.Action);
	if (e.NewItems != null)
	{
		Debug.WriteLine("Items added: ");
		foreach (var item in e.NewItems)
		{
			Debug.WriteLine(item);
		}
	}

	if (e.OldItems != null)
	{
		Debug.WriteLine("Items removed: ");
		foreach (var item in e.OldItems)
		{
			Debug.WriteLine(item);
		}
	}
}

The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.

If I run the RunObservableCollectionCode method I get the following output:

Change type: Add
Items added:
Adam
Change type: Add
Items added:
Eve
Change type: Remove
Items removed:
Adam
Change type: Add
Items added:
John
Change type: Add
Items added:
Peter
Change type: Reset

You can then decide how to handle additions and deletions in the event handler.

View all various C# language feature related posts here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.