Dictionary Entry structure

The DictionaryEntry structure defines a dictionary key/value pair in a dictionary collection that:

• Acts as a supporting type for IDictionary collections.

• Provides two public properties called Key and Value to access and specify the key and value respectively.

• Implements type safety in the custom dictionary.

The following code example shows how to implement Dictionary base types in Visual Basic and C#. You create a collection that inherits from DictionaryBase. Then, implement strongly typed methods to add an element, check if an element already exists in the collection, and remove an element from the collection. Finally, you add a method to retrieve a value by key, retrieve a collection of abbreviations, and retrieve a collection of the abbreviated phrases.

Visual Basic

public class MyAbbreviations : DictionaryBase {

public void Add(string ShortForm, string FullForm) {

this.Dictionary.Add(ShortForm, FullForm) ; }

public bool Contains(string ShortForm) {

return this.Dictionary.Contains(ShortForm); }

public void Remove(string ShortForm) {

this.Di ctionary.Remove(ShortForm); }

public string this[string ShortForm] {

return this.Dictionary[ShortForm].ToString(); }

this.Dictionary[ShortForm] = value; }

public ICollection ShortForms {

return this.Dictionary.Keys; }

public ICollection FullForms {

return this.Dictionary.Values; }

//The code above creates a class that represents a custom dictionary//

//The code snippet below implements this custom dictionary//

MyAbbreviations obj = new MyAbbreviations();

obj.Add("ANSI", "American National Standard Institute");

obj.Add("FIFO", "First In First Out");

obj.Add("LIFO", "Last In First Out");

foreach (DictionaryEntry de in obj)

Console.WriteLine("{0} = {1}", de.Key, de.Value);

Was this article helpful?

0 0

Post a comment