Amit Bisht
Amit Bisht

Reputation: 5136

c# $ string in resource

I need to add $"test message {variable1} and {variable2}" kind of string into the resource file.
Earlier this can be done using the string builder format like below

test message {0} and {1}  

Let me know is there any alternative for doing this for $ string format

Upvotes: 4

Views: 1543

Answers (1)

Paulo Morgado
Paulo Morgado

Reputation: 14846

$"test message {variable1} and {variable2}" is syntactic sugar for string.Format("test message {0} and {1}", variable1, variable2).

You can only put static values in resources. You can't put dynamic values as a formatted string from dynamic values.

If you REALLY want to use string interpolation for this, you need to key your resources with the formats and do something like this:

string R(FormattableString fs)
{
    return string.Format(Resources.GetString(fs.Format), fs.GetArguments());
}

// uses "test message {0} and {1}" as resource key
R($"test message {variable1} and {variable2}");

Upvotes: 5

Related Questions