Search code examples
c#resourcesglobalization

How to get Resources Key string value by passing only the Resources.MyProperty property


I have a standard resources file where the auto-generated source code produces lines of this type:

/// <summary>
///   Looks up a localized string similar to Database Error.
/// </summary>
internal static string DatabaseError {
    get {
        return ResourceManager.GetString("DatabaseError", resourceCulture);
    }
}

/// <summary>
///   Looks up a localized string similar to Invalid Login.
/// </summary>
internal static string InvalidLogin {
    get {
        return ResourceManager.GetString("InvalidLogin", resourceCulture);
    }
}

I have a place that loop through all the resource file and obtains the Key and value of all the entries and stores them in the DB. I have this because the translation are going to be maintained by the client without needing to make a new version everytime that someone wants to rename a value or simply because the system offers a new language.

Now, I need to make an easy access to these translations and I do not want to use the option 1, but the option 2 (something on this lines, where I use the resources property and not a string).

Option 1 // the one I do not want to use

var txt= translationService.GetTranslation("DatabaseError", UserContext.LanguageId);

Option 2 // the Kind of solution I am trying to use

var txt= translationService.GetTranslation(Resources.DatabaseError, UserContext.LanguageId);

The "style" of option 2, allows the programmer to not care about strings. Strings are prone to mistakes/bugs and by using the existing property the compiler knows when something is non longer valid.

The problem, is that by accessing this property I am getting the "translated" value form the resource file .... and I simply do not want to try to match this text with an existing resource key... Not only because this is not efficient but also does not insure non duplicated values....

Another solution, but this one I really do NOT want to use is: make my own "ResourcesClassMapping class" that keeps the "string" values there and make this mapping.... I simply do not want to keep track of the string key values, to know if they are new old or updated.

How can I do this in a pretty and elegant way?


Solution

  • Well, while I am waiting for some feedback and possibly other solutions/approaches, I was able to find a not so bad option:

    public static string GetTranslation(Expression<Func<string>> expr)
    {
        if (!(expr.Body is MemberExpression member)) return "";
        var property = member.Member as PropertyInfo;
        if (property == null) return "";
    
        var key = property.Name;
    
        // TODO: using the key name I can get the value from the DB/cache
        var finalTranslation = ""; 
    
        return finalTranslation;
    }
    
    //and I call it like this:
    var txt = GetTranslation(() => Resources.Resources.InvalidLogin);