eBabel Blog

Make a website

Strongly Typed SortedList(TKey, TValue)

16 March 2010

The SortedList signature allows it to be strongly typed, i.e. key/values where the object type of the value is checked. It represents a collection of key/value pairs that are sorted by key based on the associated IComparer(T) implementation.

Namespace: System.Collections.Generic
Assembly: System (in System.dll)

[SerializableAttribute]
[ComVisibleAttribute(false)]
public class SortedList : IDictionary,
	ICollection>, IEnumerable>,
	IDictionary, ICollection, IEnumerable

Source: Microsoft

For example the following code compiles and runs:

SortedList openWith = new SortedList();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

and as expected this returns

For key = "rtf", value = wordpad.exe.

However the following code will not even compile:

SortedList openWith = new SortedList();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe"); openWith.Add("rtf", 123);
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

the build process fails with errors:

The best overloaded method match for 'System.Collections.Generic.SortedList.Add(string, string)' has some invalid arguments C:\Users\[path]\Program.
Cannot convert from 'int' to 'string'.

If you liked this blog post, you may want to subscribe to my news feed in your RSS reader.