26 August 2011

C# - A basic localization system

For small tools I don't want to setup resource files for localization, so I developed this basic one-class system that's very easy to setup and use.

The dictionary

First off, a language enum:
public enum Language {
  Dutch = 0,
  English = 1,
  French = 2
}

Then the static class that does the rest:
public static class Dictionary {
  public static Language Language { get; set; }

  public static string Book {
    get { return GetEntry("Boek", "Book", "Livre"); }
  }

  private static string GetEntry(params string[] entries) {
    if (entries.Length > (int)Language)
      return entries[(int)Language];
    else
      return string.Empty;
  }
}

The Language parameter must be set first.
The actual literals are static properties that can be used just like they are in a resource file.
The GetEntry method helps the literals to return the right translation.

Usage

Usage of this class is very simple.
First set the language you want to use:
Dictionary.Language = theUsersLanguage;

Then use the dictionary like a resource file:
this.Title = Dictionary.Book;

No comments:

Post a Comment