2

I know two methods to get string from resource files.

Method 1: Directly access.

string str = _NAMESPACE.Properties.Resources.HelloWorld;

Method 2: Via ResourceManager.

ResourceManager rm = new ResourceManager("_NAMESPACE.Properties.Resources", Assembly.GetExecutingAssembly());
string str = rm.GetString("HelloWorld");

If there are multiple localizing resources files, both these two methods would get correct localizing string.

If I made a typing mistake in string key, method1 would fail while building. Method2 will fail until run time. For this reason, I think method1 is better than method2.

I found some similar questions in this forum. However, I still can't get good answer for my question.

  1. Why is it better to call the ResourceManager class as opposed to loading resources directly by name?

  2. Need to use ResourceManager + GetString to support cultures OR I can just point directly at the resource file?

Is method1 really better?

Community
  • 1
  • 1
Mystic Lin
  • 365
  • 4
  • 15
  • 2
    Look at all those hard-coded strings in the second code! The first one is much more refactor-friendly. – Ben Voigt Sep 24 '16 at 23:42
  • If you wish to divide your resources among *multiple* resource files (e.g., `Properties.Messages`, `Properties.Icons`, etc.), see [this question](http://stackoverflow.com/q/5246631/1497596) and its answers. – DavidRR Jan 09 '17 at 14:21

1 Answers1

2

I believe the first method is better because when you use the second method you are creating a new instance of the resource manager which I would think is an unnecessary use of memory.

Edit*

After reading this article: https://msdn.microsoft.com/en-us/library/7k989cfy(v=vs.90).aspx

It seems they are basically the same, when accessing resources directly with the resources class, internally a resource manager class is used to create an instance of the object.

Raevan
  • 46
  • 5
  • 2
    You're absolutely right that both use the `ResourceManager` class, but that doesn't negate your point about creating a new instance in snippet 2. The first version creates one instance and reuses it as many times as necessary. – Ben Voigt Sep 24 '16 at 23:49
  • @BenVoigt Ah, thanks for the confirmation, this was my original train of thought and after thinking to hard on it I began to doubt myself. – Raevan Sep 25 '16 at 04:02