2
I am trying to recover a class value using interpolation. Using Console.WriteLine($"Meu Nome é, {pessoa.Nome}");
, I get the value of the form I want, but in my case the string
will come from a database configuration.
I tried to ride it like this
string expressao = "Meu Nome é, {pessoa.Nome}";
and call it that
Console.WriteLine($"" + (expressao));
This prints the string
My Name is, {person. Name}
And that’s not what I want. Is there any way to do that?
using System;
namespace Usando_Interpolacao
{
class Program
{
static void Main(string[] args)
{
var pessoa = new Pessoa()
{
Documento = new Documento()
{
Numero = 12345,
Tipo = "RG"
},
Idade = 20,
Nome = "Papai Noel",
};
string expressao = "Meu Nome é, {pessoa.Nome}";
Console.WriteLine($"Meu Nome é, {pessoa.Nome}"); // print --> Meu Nome é, Papai Noel
Console.WriteLine($"" + (expressao)); // print --> Meu Nome é, {pessoa.Nome} .. Errado :(
Console.ReadKey();
}
}
public class Pessoa
{
public int Idade { get; set; }
public string Nome { get; set; }
public Documento Documento { get; set; }
}
public class Documento
{
public int Numero { get; set; }
public string Tipo { get; set; }
}
}
and
expressao = $"Meu Nome é, {pessoa.Nome}";
dps,Console.WriteLine(expressao);
?– Rovann Linhalis
There is no way because interpolation is solved at compile time. That is, tokens need to be known beforehand. The final code is a
string.Format
default. What you can do is build a method to dynamically solve tokens.– Jéf Bueno
Related: What does the symbol "$" mean before a string?
– Jéf Bueno
Related: Library equal to C# 6.0 runtime Interpolation string
– Jéf Bueno
You need something that does the "parse" or "evaluate" of your expression for that. Take a look at this package that does just that: https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples
– Ricardo Pontual
With this package, your code would look like this:
var resultado = await CSharpScript.EvaluateAsync<string>(expressao);
– Ricardo Pontual
@LINQ, cool that mustache link, I’m gonna go check out these libraries he referenced.
– Marco Souza