How to use string interpolation in a resource file?
Asked Answered
E

2

18

I would like to use a resource file to send an email. In my resource file I used a variable "EmailConfirmation" with the value "Hello {userName} ... "

In my class I used:

public static string message (string userName)
{
   return Resource.WebResource.EmailConfirmation
}

The problem is that the return says "Hello {userName}" instead of "Hello Toto".

Efferent answered 17/2, 2018 at 19:46 Comment(1)
String interpolation only works with string literals.Interlunation
P
32

You can't make use of string interpolation in the context of resources. However you could achieve that you want by making use of string.Format. Write to your resource file something like this:

Hello {0}

and then use it like below:

public static string message (string userName)
{
   return string.Format(Resource.WebResource.EmailConfirmation, userName);
}

Update

You can add as many parameters as you want. For instance:

Hello {0}, Confirm your email: {1}

And then you can use it as:

string.Format(Resource.WebResource.EmailConfirmation
    , userName
    , HtmlEncoder.Default.Encode(link))
Pye answered 17/2, 2018 at 19:55 Comment(1)
yes, I thought of it, but it actually is more complex because in my variable "EmailConfirmation" I used this : "Hello {userName}, Confirm your email : {HtmlEncoder.Default.Encode(link)}" And "HtmlEncoder.Default.Encode" is not taken in cociderationEfferent
T
1

If you really want to use placeholders like that instead of digits (I understand...) then you can do this:

return Resource.WebResource.EmailConfirmation.Replace("{userName}",userName)

You can keep daisychaining .Replace commands for additional placeholders that you use.

return Resource.WebResource.EmailConfirmation.Replace("{userName}",userName).Replace("{loginDate}",loginDate).Replace("{notes}",notes)
Tadtada answered 23/1 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.