Strongly-Typed Resources in the .NET Framework 2.0

Release 1.0 - ...

Recall the code that retrieves the resource string:

C# CopyCode image Copy Code
MessageBox.Show(resourceManager.GetString("InsufficientFunds"));

This line is fragile. It relies upon a string, “InsufficientFunds”, to identify the resource string. If this string includes a typo, the code will still compile successfully, but it will throw an exception at runtime. The problem is that this string cannot be verified at compile time, so it is a fragile solution. A better solution is one that the compiler can verify. To solve this problem Visual Studio 2005 introduces Strongly-Typed Resources. A strongly-typed resource is to resources what a strongly-typed dataset is to DataSets; it is a generated class that includes the resource key names as properties. The line of code can be rewritten to use a strongly-typed resource:

C# CopyCode image Copy Code
MessageBox.Show(Form1Resources.InsufficientFunds);

Form1Resources is a strongly-typed resource class in which each resource entry is represented by a property (i.e., “InsufficientFunds”, in this example). The Form1.resourceManager field is no longer needed and can be removed completely. When a resource file is created in Visual Studio 2005, a corresponding file with the extension “.Designer.cs” is also created, so Form1Resources.resx has a corresponding file called Form1Resources.Designer.cs. You can see this in Solution Explorer by expanding the .resx node. As you add, edit, or delete entries in the resx file, the designer file is updated. If you double-click the file, you will see the generated class.

The class encapsulates its own ResourceManager object in a private static field called resourceMan. For each entry in the .resx file, a static property is created to return the resource’s value. The resourceCulture private static field is initially null (therefore, ResourceManager uses Thread.CurrentThread.CurrentUICulture). You can set its equivalent static property, Culture, to specify that it should retrieve resources for a different culture. Although this is rare, you might, for example, want to display more than one culture at the same time.