C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Also: The Dictionary doesn't need to be created in multiple instances. Only one instance is needed.
GetPlural: Access to the string keys and values is provided through the public method GetPlural.
Public, privateExample: This code will return the value in the static Dictionary that is found at the key specified.
C# program that uses static Dictionary
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Write pluralized words from static Dictionary
Console.WriteLine(PluralStatic.GetPlural("game"));
Console.WriteLine(PluralStatic.GetPlural("item"));
Console.WriteLine(PluralStatic.GetPlural("entry"));
}
}
/// <summary>
/// Contains plural logic in static class [separate file]
/// </summary>
static class PluralStatic
{
/// <summary>
/// Static string Dictionary example
/// </summary>
static Dictionary<string, string> _dict = 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>
/// Access the Dictionary from external sources
/// </summary>
public static string GetPlural(string word)
{
// Try to get the result in the static Dictionary
string result;
if (_dict.TryGetValue(word, out result))
{
return result;
}
else
{
return null;
}
}
}
Output
games
items
entries
Tip: If one dictionary can be shared among many class instances, often performance will improve.
Review: The discussion focuses on the static Dictionary. It points to a more complete word pluralization lookup table.