This documentation is archived and is not being maintained.

SortedList<TKey, TValue> Constructor

Initializes a new instance of the SortedList<TKey, TValue> class that is empty, has the default initial capacity, and uses the default IComparer<T>.

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

public SortedList()

Every key in a SortedList<TKey, TValue> must be unique according to the default comparer.

This constructor uses the default value for the initial capacity of the SortedList<TKey, TValue>. To set the initial capacity, use the SortedList<TKey, TValue>(Int32) constructor. If the final size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the SortedList<TKey, TValue>.

This constructor uses the default comparer for TKey. To specify a comparer, use the SortedList<TKey, TValue>(IComparer<TKey>) constructor. The default comparer Comparer<T>.Default checks whether the key type TKey implements System.IComparable<T> and uses that implementation, if available. If not, Comparer<T>.Default checks whether the key type TKey implements System.IComparable. If the key type TKey does not implement either interface, you can specify a System.Collections.Generic.IComparer<T> implementation in a constructor overload that accepts a comparer parameter.

This constructor is an O(1) operation.

The following code example creates an empty SortedList<TKey, TValue> of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

This code example is part of a larger example provided for the SortedList<TKey, TValue> class.

// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith = 
    new SortedList<string, string>();

// Add some elements to the list. There are no 
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is 
// already in the list.
    openWith.Add("txt", "winword.exe");
catch (ArgumentException)
    Console.WriteLine("An element with Key = \"txt\" already exists.");

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.