Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the literal resource key with the ResourceManager and nameof operator

I have to access my resource files weakly typed, that means I have to load/access the resources with the ResourceManager passing the full namespace + filename.

 var rm = new ResourceManager("namespace.name.locale.brand", Assembly.GetExecutingAssembly());

I access my resource image via 'myImage' in a non refactoring safe method.

string imageUrl = rm.GetString("myImage");

Just imagine I have many .resx files with different locale/brand name. They all have different images but they have the same keys. Thus I can not access those resources static typed as I just know the correct resource at runtime.

But my hope there is a tricky way with a combination of nameof operator and the resource manager instance.

Anyone know that tricky way?

Please do NOT suggest to access ANY of those .resx files in a static typed way and pass that key with nameof to the above .GetString() method.

if there is no solution with nameof operator any tool is welcome THEN too ;-)

like image 464
HelloWorld Avatar asked Dec 21 '25 23:12

HelloWorld


1 Answers

Since you do not want to have static typed resource, there is no other way than manually updating the code.

However, you can still create a wrapper to access the resources. By creating a wrapper, you can centralize the access within one single file, and you can also use rename F2 to change it once for all.

public class ResourceWrapper
{
    private ResourceManager rm;

    public ResourceWrapper(string name) :
        this(name, Assembly.GetCallingAssembly())
    {
    }
    public ResourceWrapper(string name, Assembly assembly)
    {
        rm = new ResourceManager(name, assembly);
    }

    public string myImage => rm.GetString(nameof(myImage));
}

Or, you can statically link to one of the resource files and use it as the name provider for nameof. Like :

string imageUrl = rm.GetString(nameof(DummyResource.myImage));
like image 95
Xiaoy312 Avatar answered Dec 23 '25 11:12

Xiaoy312



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!