-7

If we can one store the temp_data of a string in a variable and use interpolation on it?

var name = "John";

var temp_data = "Hi {name}";

var result_data = $temp_data;

If their any possible solution are available other than string.Format() and string.Replace()

Maciej S.
  • 752
  • 10
  • 22

4 Answers4

3

If you wish to store the message as an external resource you will need to use string.Format rather than string interpolation, interpolated strings have to exist in their entirety at compile time as string literals.

You will also need to ensure that the number of variables contained in the message match those in the code calling string.format otherwise it will not transpose correctly.

As an example, this is using a resource file;

var message = string.Format(Strings.ErrorMessage, value1, value2);

Strings.ErrorMessage would contain;

"This is the error {0} and message {1}"

ChrisBint
  • 12,773
  • 6
  • 40
  • 62
  • 1
    @Leogiciel No, because you can't when using an message that is external to the code (db/resource file) as explained in my answer. – ChrisBint Jan 02 '19 at 12:32
  • You're right, I definitely misunderstood this poorly-explained use-case. String.Format is then the right solution, +1 kudos. – Leogiciel Jan 02 '19 at 12:40
-1

you can use $ - string interpolation (C# Reference) https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

hamed hossani
  • 986
  • 2
  • 14
  • 33
-2

you can use like this

double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);

string messageInInvariantCulture = FormattableString.Invariant(message);

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
divyang4481
  • 1,584
  • 16
  • 32
-3

Using C#6, you can do exactly what you wrote, without the typo :

var name = "John";

var temp_data = $"Hi {name}";

var result_data = temp_data;

Console.log(result_data);

will return "Hi John" ;)

Leogiciel
  • 263
  • 2
  • 10