Overview
The DictionaryBase
class provides a base implementation for a strongly typed dictionary that maps keys to values. It simplifies the creation of custom dictionary classes by handling much of the standard dictionary functionality.
Syntax
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
Inherits from Object
. Implements the following interfaces:
IDictionary
ICollection
IEnumerable
Examples
C#
VB.NET
using System;
using System.Collections;
public class MyDictionary : DictionaryBase
{
public void Add(string key, string value) => Dictionary.Add(key, value);
public string this[string key]
{
get => (string)Dictionary[key];
set => Dictionary[key] = value;
}
public void Remove(string key) => Dictionary.Remove(key);
public ICollection Keys => Dictionary.Keys;
public ICollection Values => Dictionary.Values;
}
class Program
{
static void Main()
{
var dict = new MyDictionary();
dict.Add("One", "1");
dict.Add("Two", "2");
Console.WriteLine(dict["One"]);
}
}
Imports System
Imports System.Collections
Public Class MyDictionary
Inherits DictionaryBase
Public Sub Add(key As String, value As String)
Dictionary.Add(key, value)
End Sub
Default Public Property Item(key As String) As String
Get
Return DirectCast(Dictionary(key), String)
End Get
Set(value As String)
Dictionary(key) = value
End Set
End Property
Public Sub Remove(key As String)
Dictionary.Remove(key)
End Sub
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
End Class
Module Module1
Sub Main()
Dim dict As New MyDictionary()
dict.Add("One", "1")
dict.Add("Two", "2")
Console.WriteLine(dict("One"))
End Sub
End Module
Remarks
When inheriting from DictionaryBase
, you must provide the implementation for the required members as shown in the examples. The base class handles synchronization, enumeration, and collection semantics.