Home
C#
IDictionary Use, Generic Interface
Updated Oct 26, 2021
Dot Net Perls
IDictionary. How can we use the C# IDictionary interface? Many lookup types (Dictionary, SortedDictionary) implement the IDictionary interface.
C# interface notes. We can make types that implement IDictionary. But it is useful too as an abstraction—we can accept IDictionary as a parameter type.
Dictionary
interface
Example. This program uses Dictionary and SortedDictionary. Suppose that you want to add some functionality that can work on an instance of Dictionary or an instance of SortedDictionary.
Tip This code only needs to be written once if you have it use the IDictionary type.
Next The WriteKeyA method works equally well on Dictionary and SortedDictionary instances.
using System; using System.Collections.Generic; class Program { static void Main() { // Dictionary implements IDictionary. Dictionary<string, string> dict = new Dictionary<string, string>(); dict["A"] = "B"; WriteKeyA(dict); // SortedDictionary implements IDictionary. SortedDictionary<string, string> sort = new SortedDictionary<string, string>(); sort["A"] = "C"; WriteKeyA(sort); } static void WriteKeyA(IDictionary<string, string> i) { // Use instance through IDictionary interface. Console.WriteLine(i["A"]); } }
B C
Fields and variables. It is also possible to have fields of type IDictionary. This can make it possible to have a class that can use any dictionary type without worrying about which one it is.
class
Tip You could even later implement a custom Dictionary type and never need to change this class. Variables can use type IDictionary.
Discussion. The IDictionary type has many required methods. The Dictionary type itself is good at what it does. An alternative implementation would not be of much use in most programs.
Further Even the alternatives in the .NET Framework, such as SortedDictionary, are typically not useful.
SortedDictionary
Summary. IDictionary can be used in an implementation of a custom dictionary. It can also be used in programs that act upon different dictionary types including Dictionary and SortedDictionary.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 26, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen