Dot Net Perls
C#

Static Dictionary Example

by Sam Allen

Problem

Simplify string lookups by using a static Dictionary of plural words in your applications. We need to encapsulate the logic for pluralization in a Windows Forms GUI, using a simple static data storage object. This must provide constant lookup time and be compact.

Solution: C#

Static dictionaries are ideal for pluralization. First, the topic of making plurals in human languages is enormously complex. I am only fluent in English, but I know that Chinese, Russian, and many other languages have pluralization rules that are vastly different. Our solution is tailored for English usage.

Implementation

In C# you have the ability to declare objects, such as generics or arrays, in an intuitive and clean syntax, called collection initializers. This is very useful if you need to declare these sorts of objects in your source files. Here is the code, beginning with the data storage and ending with the methods.

using System;
using System.Diagnostics;
using System.Collections.Generic;

/// <summary>
/// This static class stores plural words and has a method that will
/// return a plural version of a certain word if the count of
/// that word is not equal to 1.
/// </summary>
static class Plurals
{
    /// <summary>
    /// Stores singular words and their plural equivalent in a dictionary.
    /// You will need to change this to add new plurals.
    /// </summary>
    static Dictionary<string, string> _pluralTable =
        new Dictionary<string, string>
    {
        {"entry", "entries"},
        {"image", "images"},
        {"view", "views"},
        {"file", "files"},
        {"result", "results"},
        {"word", "words"},
        {"definition", "definitions"},
        {"item", "items"},
        {"megabyte", "megabytes"},
        {"game", "games"}
    };   

    /// <summary>
    /// Call this method to get the properly pluralized American
    /// English version of the word.
    /// </summary>
    /// <param name="word">The word needing conditional pluralization.</param>
    /// <param name="count">The number of items the word refers to.</param>
    /// <returns>The properly pluralized string.</returns>
    static public string Plural(string word, int count)
    {
        if (count == 1)
        {
            return word;
        }
        else
        {
            return _pluralTable[word]; // Lookup value
        }
    }

    /// <summary>
    /// Return a plural phrase, such as "3 dogs" or "1 cat".
    /// This is the preferred function as it is less likely
    /// to be called incorrectly.
    /// </summary>
    /// <param name="word">The noun that may need to be pluralized.</param>
    /// <param name="count">The number of instances of the noun.</param>
    /// <returns>A string such as "3 dogs" or "1 cat." Use for a UI string.</returns>
    static public string PluralPhrase(string word, int count)
    {
        string properPlural = Plural(word, count);
        return count.ToString() + " " + properPlural;
    }
}

How do I use it?

Change the static Dictionary to include the words you need in your program, first. Then, you can simply call into the static class methods. You don't want to use new to create a new object. You want to use code that looks similar to the following.

/// <summary>
/// Example program class.
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Plurals.PluralPhrase("item", 2));
        Console.WriteLine(Plurals.PluralPhrase("game", 1));
        Console.WriteLine(Plurals.Plural("item", 1));
    }
}

Ineffective solutions

For the longest time, I would write code that would simply do an if or a ternary operation. But this is not ideal. In a high-quality program, you want to have the minimum of explicit branches--you want to abstract all the pluralization logic out of the task at hand. You don't want to have if-statements for plurals when you want the code to be focused on counting widgets.

Conclusion

View this code at my source code viewer. There are more advanced projects dealing with this, such as the gettext GNU utilities. Some programs like Mozilla Firefox have problems in this area for their extensions. I have no clue what Russian programmers do, as I think Russian has some difficult rules.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge