Library equal to C# 6.0 runtime Interpolation string

Asked

Viewed 157 times

4

Does anyone know of a library that interpolates at runtime on strings?

I know it could be done using Replace(), but I don’t want to pass the list with all the variables.

For example:

Programa de classe
{
    const string interpolados = $ "{FirstName}"; 
    // variável *FirstName* não existe no contexto atual

     static void Main (string [] args)
     {
        var firstName = "fred";
        Console.WriteLine (interpolado);
        Console.ReadKey ();
     }
}

interpolados can also be a text with several variables.

How to do something similar?

  • Related: http://stackoverflow.com/a/29068642/221800

1 answer

6


It is not necessary any library, the . NET has always had this resource. In fact the interpolation shown is new and few know. This is the first time I meet someone who knows the new resource and not the old one.

It may not be well with the syntax you want, but this syntax to solve at runtime is even bad and induces errors and couple names that not always the code can guarantee.

Technically it is possible to make a library that accepts variable names instead of parameter numbers, but I see no advantages.

Note that the example shown is not possible to do anything because you would have to pass the parameter at runtime. Actually not even using C# 6 interpolation this code works.

What you want is what’s done with string.Format(). The same that has always been used internally in a WriteLine(), for example.

var texto = string.Format("{0}", firstname);

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

C# 6 interpolation uses a simpler syntax with the help of the compiler. I talk about it in the question What does the symbol "$" mean before a string?

I’m going to quote some libraries, but think 10 times before you adopt them, it might sound good, but it’s not what you need. I don’t know them, I can’t talk about their quality:

Has a code in CR.SE that can serve as inspiration to make the mechanism itself (it is not easy to think of everything).

  • Thank you very much

  • Thanks, this project solved the OS problem: https://github.com/little-sharps/string_format.

  • 1

    @bigown, one more altenativa: Handlebars.NET

Browser other questions tagged

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