Export (0) Print
Expand All

DictionaryBase Class

Provides the abstract (MustInherit in Visual Basic) base class for a strongly typed collection of key-and-value pairs.

For a list of all members of this type, see DictionaryBase Members.

System.Object
   System.Collections.DictionaryBase
      Derived classes

[Visual Basic]
<Serializable>
MustInherit Public Class DictionaryBase
   Implements IDictionary, ICollection, IEnumerable
[C#]
[Serializable]
public abstract class DictionaryBase : IDictionary, ICollection,
   IEnumerable
[C++]
[Serializable]
public __gc __abstract class DictionaryBase : public IDictionary,
   ICollection, IEnumerable
[JScript]
public
   Serializable
abstract class DictionaryBase implements IDictionary,
   ICollection, IEnumerable

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

This implementation does not provide a synchronized (thread-safe) wrapper for a DictionaryBase, but derived classes can create their own synchronized versions of the DictionaryBase using the SyncRoot property.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Remarks

[Visual Basic, C#] The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the DictionaryBase is a key-and-value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:

[C#] 
foreach (DictionaryEntry myDE in myDictionary) {...}
[Visual Basic] 
Dim myDE As DictionaryEntry
For Each myDE In myDictionary
   ...
Next myDE

[Visual Basic, C#] The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Notes to Implementers:  

This base class is provided to make it easier for implementers to create a strongly typed custom collection. Implementers should extend this base class instead of creating their own.

Members of this base class are protected and are intended to be used through a derived class only.

Example

[Visual Basic, C#, C++] The following code example implements the DictionaryBase class and uses that implementation to create a dictionary of String keys and values that have a Length of 5 characters or less.

[Visual Basic] 
Imports System
Imports System.Collections

Public Class ShortStringDictionary
   Inherits DictionaryBase

   Default Public Property Item(key As [String]) As [String]
      Get
         Return CType(Dictionary(key), [String])
      End Get
      Set
         Dictionary(key) = value
      End Set
   End Property

   Public ReadOnly Property Keys() As ICollection
      Get
         Return Dictionary.Keys
      End Get
   End Property

   Public ReadOnly Property Values() As ICollection
      Get
         Return Dictionary.Values
      End Get
   End Property

   Public Sub Add(key As [String], value As [String])
      Dictionary.Add(key, value)
   End Sub 'Add

   Public Function Contains(key As [String]) As Boolean
      Return Dictionary.Contains(key)
   End Function 'Contains

   Public Sub Remove(key As [String])
      Dictionary.Remove(key)
   End Sub 'Remove

   Protected Overrides Sub OnInsert(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnInsert

   Protected Overrides Sub OnRemove(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If
   End Sub 'OnRemove

   Protected Overrides Sub OnSet(key As [Object], oldValue As [Object], newValue As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not newValue.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("newValue must be of type String.", "newValue")
      Else
         Dim strValue As [String] = CType(newValue, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("newValue must be no more than 5 characters in length.", "newValue")
         End If
      End If
   End Sub 'OnSet

   Protected Overrides Sub OnValidate(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnValidate 

End Class 'ShortStringDictionary


Public Class SamplesDictionaryBase

   Public Shared Sub Main()

      ' Creates and initializes a new DictionaryBase.
      Dim mySSC As New ShortStringDictionary()

      ' Adds elements to the collection.
      mySSC.Add("One", "a")
      mySSC.Add("Two", "ab")
      mySSC.Add("Three", "abc")
      mySSC.Add("Four", "abcd")
      mySSC.Add("Five", "abcde")

      ' Tries to add a value that is too long.
      Try
         mySSC.Add("Ten", "abcdefghij")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      ' Tries to add a key that is too long.
      Try
         mySSC.Add("Eleven", "ijk")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine()

      ' Displays the contents of the collection using the enumerator.
      Console.WriteLine("Initial contents of the collection:")
      PrintKeysAndValues(mySSC)

      ' Searches the collection with Contains.
      Console.WriteLine("Contains ""Three"": {0}", mySSC.Contains("Three"))
      Console.WriteLine("Contains ""Twelve"": {0}", mySSC.Contains("Twelve"))
      Console.WriteLine()

      ' Removes an element from the collection.
      mySSC.Remove("Two")

      ' Displays the contents of the collection using the Keys property.
      Console.WriteLine("New state of the collection:")
      PrintKeysAndValues3(mySSC)

   End Sub 'Main

   ' Uses the enumerator. 
   Public Shared Sub PrintKeysAndValues(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
         If Not (myEnumerator.Current Is Nothing) Then
            myDE = CType(myEnumerator.Current, DictionaryEntry)
            Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
         End If
      End While
      Console.WriteLine()
   End Sub 'PrintKeysAndValues

   ' Uses the foreach statement which hides the complexity of the enumerator.
   Public Shared Sub PrintKeysAndValues2(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      For Each myDE In  myCol
         Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
      Next myDE
      Console.WriteLine()
   End Sub 'PrintKeysAndValues2

   ' Uses the Keys property and the Item property.
   Public Shared Sub PrintKeysAndValues3(myCol As ShortStringDictionary)
      Dim myKeys As ICollection = myCol.Keys
      Dim k As [String]
      For Each k In  myKeys
         Console.WriteLine("   {0,-5} : {1}", k, myCol(k))
      Next k
      Console.WriteLine()
   End Sub 'PrintKeysAndValues3

End Class 'SamplesDictionaryBase 

 
'This code produces the following output.
'
'System.ArgumentException: value must be no more than 5 characters in length.
'Parameter name: value
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'System.ArgumentException: key must be no more than 5 characters in length.
'Parameter name: key
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'
'Initial contents of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Two   : ab
'   Five  : abcde
'
'Contains "Three": True
'Contains "Twelve": False
'
'New state of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Five  : abcde


[C#] 
using System;
using System.Collections;

public class ShortStringDictionary : DictionaryBase  {

   public String this[ String key ]  {
      get  {
         return( (String) Dictionary[key] );
      }
      set  {
         Dictionary[key] = value;
      }
   }

   public ICollection Keys  {
      get  {
         return( Dictionary.Keys );
      }
   }

   public ICollection Values  {
      get  {
         return( Dictionary.Values );
      }
   }

   public void Add( String key, String value )  {
      Dictionary.Add( key, value );
   }

   public bool Contains( String key )  {
      return( Dictionary.Contains( key ) );
   }

   public void Remove( String key )  {
      Dictionary.Remove( key );
   }

   protected override void OnInsert( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

   protected override void OnRemove( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }
   }

   protected override void OnSet( Object key, Object oldValue, Object newValue )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( newValue.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "newValue must be of type String.", "newValue" );
      else  {
         String strValue = (String) newValue;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" );
      }
   }

   protected override void OnValidate( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

}


public class SamplesDictionaryBase  {

   public static void Main()  {
 
      // Creates and initializes a new DictionaryBase.
      ShortStringDictionary mySSC = new ShortStringDictionary();

      // Adds elements to the collection.
      mySSC.Add( "One", "a" );
      mySSC.Add( "Two", "ab" );
      mySSC.Add( "Three", "abc" );
      mySSC.Add( "Four", "abcd" );
      mySSC.Add( "Five", "abcde" );

      // Tries to add a value that is too long.
      try  {
         mySSC.Add( "Ten", "abcdefghij" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Tries to add a key that is too long.
      try  {
         mySSC.Add( "Eleven", "ijk" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      Console.WriteLine();

      // Displays the contents of the collection using the enumerator.
      Console.WriteLine( "Initial contents of the collection:" );
      PrintKeysAndValues( mySSC );

      // Searches the collection with Contains.
      Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) );
      Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) );
      Console.WriteLine();

      // Removes an element from the collection.
      mySSC.Remove( "Two" );

      // Displays the contents of the collection using the Keys property.
      Console.WriteLine( "New state of the collection:" );
      PrintKeysAndValues3( mySSC );

   }

   // Uses the enumerator. 
   public static void PrintKeysAndValues( ShortStringDictionary myCol )  {
      DictionaryEntry myDE;
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         if ( myEnumerator.Current != null )  {
            myDE = (DictionaryEntry) myEnumerator.Current;
            Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
         }
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   public static void PrintKeysAndValues2( ShortStringDictionary myCol )  {
      foreach ( DictionaryEntry myDE in myCol )
         Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
      Console.WriteLine();
   }

   // Uses the Keys property and the Item property.
   public static void PrintKeysAndValues3( ShortStringDictionary myCol )  {
      ICollection myKeys = myCol.Keys;
      foreach ( String k in myKeys )
         Console.WriteLine( "   {0,-5} : {1}", k, myCol[k] );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

System.ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()
System.ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()

Initial contents of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Two   : ab
   Five  : abcde

Contains "Three": True
Contains "Twelve": False

New state of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Five  : abcde

*/


[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

public __gc class ShortStringDictionary : public DictionaryBase
{
public:
   __property String* get_Item( String* key )
   {
      return __try_cast<String*>(Dictionary->Item[key]);
   }

   __property void set_Item( String* key, String* value )
   {
      Dictionary->Item[key] = value;
   }

   __property ICollection* get_Keys()
   {
      return(Dictionary->Keys);
   }

   __property ICollection* get_Values()
   {
      return(Dictionary->Values);
   }

   void Add(String* key, String* value) {
      Dictionary->Add(key, value);
   }

   bool Contains(String* key) {
      return(Dictionary->Contains(key));
   }

   void Remove(String* key) {
      Dictionary->Remove(key);
   }

protected:
   void OnInsert(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }

   void OnRemove(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }
   }

   void OnSet(Object* key, Object* oldValue, Object* newValue) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (newValue->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"newValue must be of type String.", S"newValue");
      else {
         String* strValue = __try_cast<String*>(newValue);
         if (strValue->Length > 5)
            throw new ArgumentException(S"newValue must be no more than 5 characters in length.", S"newValue");
      }
   }

   void OnValidate(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else 
      {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else 
      {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }
};

// Uses the enumerator. 
void PrintKeysAndValues(ShortStringDictionary* myCol)
{
   DictionaryEntry* myDE;
   System::Collections::IEnumerator* myEnumerator = myCol->GetEnumerator();
   while (myEnumerator->MoveNext())
      if (myEnumerator->Current != 0)
      {
         myDE = __try_cast<DictionaryEntry*>(myEnumerator->Current);
         Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      }
      Console::WriteLine();
}

// Uses the foreach statement which hides the complexity of the enumerator.
void PrintKeysAndValues2(ShortStringDictionary* myCol) 
{
   IEnumerator* myEnum = myCol->GetEnumerator();
   while (myEnum->MoveNext())
   {
      DictionaryEntry* myDE = __try_cast<DictionaryEntry*>(myEnum->Current);

      Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      Console::WriteLine();
   }
}
// Uses the Keys property and the Item property.
void PrintKeysAndValues3(ShortStringDictionary* myCol) 
{
   ICollection* myKeys = myCol->Keys;
   IEnumerator* myEnum = myKeys->GetEnumerator();
   while (myEnum->MoveNext())
   {
      String* k = __try_cast<String*>(myEnum->Current);

      Console::WriteLine(S" {0, -5} : {1}", k, myCol->Item[k]);
      Console::WriteLine();
   }
}

int main() 
{
   // Creates and initializes a new DictionaryBase.
   ShortStringDictionary* mySSC = new ShortStringDictionary();

   // Adds elements to the collection.
   mySSC->Add(S"One", S"a");
   mySSC->Add(S"Two", S"ab");
   mySSC->Add(S"Three", S"abc");
   mySSC->Add(S"Four", S"abcd");
   mySSC->Add(S"Five", S"abcde");

   // Tries to add a value that is too long.
   try
   {
      mySSC->Add(S"Ten", S"abcdefghij");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   // Tries to add a key that is too long.
   try
   {
      mySSC->Add(S"Eleven", S"ijk");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   Console::WriteLine();

   // Displays the contents of the collection using the enumerator.
   Console::WriteLine(S"Initial contents of the collection:");
   PrintKeysAndValues(mySSC);

   // Searches the collection with Contains.
   Console::WriteLine(S"Contains \"Three\": {0}", __box(mySSC->Contains(S"Three")));
   Console::WriteLine(S"Contains \"Twelve\": {0}", __box(mySSC->Contains(S"Twelve")));
   Console::WriteLine();

   // Removes an element from the collection.
   mySSC->Remove(S"Two");

   // Displays the contents of the collection using the Keys property.
   Console::WriteLine(S"New state of the collection:");
   PrintKeysAndValues3(mySSC);
}

/* 
This code produces the following output.

System::ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()
System::ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()

Initial contents of the collection:
One   : a
Four  : abcd
Three : abc
Two   : ab
Five  : abcde

Contains S"Three": True
Contains S"Twelve": False

New state of the collection:
One   : a
Four  : abcd
Three : abc
Five  : abcde

*/

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Collections

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

DictionaryBase Members | System.Collections Namespace | System.Collections.Hashtable | System.Collections.IDictionary | Performing Culture-Insensitive String Operations

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft