ASP.NET: two ways to access global resource programmatically

400_the_cat picture 400_the_cat · Jul 8, 2010 · Viewed 14.2k times · Source

I know that I can set a Label's text by using the following syntax.

lblMessage.Text = (string)GetGlobalResourceObject("resxFile", "message");

What are the benefits and drawbacks associated with using the below syntax?

lblMessage.Text = Resources.resxFile.message;

The second method will not work for local resource files. Is there a different syntax for local resource files?

Answer

Hugh Jeffner picture Hugh Jeffner · Jul 13, 2010

The second way looks better because it is strongly-typed. If you changed the resource file name or the resource value name then you would get a compile error. If you needed to dynamically get a resource, then you would have to do it the first way, else use a switch statement or something similar.

If you are using asp.net 2.0 or higher there is actually a 3rd way to set a label by using markup only:

<asp:Label ID="Label1" runat="server" Text="<%$ Resources:resxFile,message %>" />

Kinda related to localization: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/localization/localization.aspx