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

Posted on

Question :

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

But I noticed that in all cases where it is used, the syntax works for directly declared strings, like this:

   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 $ after the declaration.

Approximate example:

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

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

Would it be possible to apply the same effect as $ to string template later?


What I want to do would be more or less like String.Format already does, but wanted with named parameters.


Answer :

The quick answer: you can not. The interpolation of string ( $ ) works immediately, it can not be done dynamically.

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


Leave a Reply

Your email address will not be published. Required fields are marked *