Is it possible to interpolate a string already declared in C#?

Asked

Viewed 54 times

3

The question What does the symbol "$" mean before a string? , explains that it is possible to interpolate strings in C# through the $ (dollar sign).

However, I noticed that, in all cases where it is used, the syntax works for directly declared strings, thus:

   string nome = "Wallace Maxters";

   $"Meu nome é {nome}";

But I needed to do something like this, using an existing string. I mean, I already have a string ready and I want to use it with the $ after the declaration.

Approximate example:

 string template = "Meu nome é {nome}";

 usarTemplate(template); // Faz a mesma coisa que o $ fez no exemplo anterior

It would be possible to apply the same effect as $ in na string template, subsequently?

Updating

What I wish to do would be more or less similar to what the String.Format already does, but wanted with the parameters named.

  • You want to "declare a variable" in it and change afterwards?

  • @Barbetta yes, more or less equal is possible to do with String.Format. For example: String.Format(stringExistente, valor1, valor2)

1 answer

0

The quick response: can not. The interpolation of string ($) works in the immediate, it is not possible to do it dynamically.

If you use the string.Format("{0}") yes, then you can do more things "funny".

  • It wouldn’t help much. The String.Format works by sequential parameterization. This would be hell to do an Email template, for example.

  • Yes, it’s sequential, it’s one of the "drawbacks".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.