C#6.0 String Interpolation Localization

C#6.0 string interpolation localization

Using the Microsoft.CodeAnalysis.CSharp.Scripting package you can achieve this.

You will need to create an object to store the data in, below a dynamic object is used. You could also create an specific class with all the properties required. The reason to wrap the dynamic object in a class in described here.

public class DynamicData
{
public dynamic Data { get; } = new ExpandoObject();
}

You can then use it as shown below.

var options = ScriptOptions.Default
.AddReferences(
typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly,
typeof(System.Runtime.CompilerServices.DynamicAttribute).GetTypeInfo().Assembly);

var globals = new DynamicData();
globals.Data.Name = "John";
globals.Data.MiddleName = "James";
globals.Data.Surname = "Jamison";

var text = "My name is {Data.Name} {Data.MiddleName} {Data.Surname}";
var result = await CSharpScript.EvaluateAsync<string>($"$\"{text}\"", options, globals);

This is compiling the snippet of code and executing it, so it is true C# string interpolation. Though you will have to take into account the performance of this as it is actually compiling and executing your code at runtime. To get around this performance hit if you could use CSharpScript.Create to compile and cache the code.

Is there a way to use C# 6's String Interpolation with multi-line string?

Try swapping the places of $ and @.

Does C# 6.0's String interpolation rely on Reflection?

No. It doesn't. It is completely based on compile-time evaluation.

You can see that with this TryRoslyn example that compiles and decompiles this:

int name = 4;
string myStr = $"Hi {name}, how are you?";

Into this:

int num = 4;
string.Format("Hi {0}, how are you?", num);

string interpolation also supports using IFormattable as the result so (again using TryRoslyn) this:

int name = 4;
IFormattable myStr = $"Hi {name}, how are you?";

Turns into this:

int num = 4;
FormattableStringFactory.Create("Hi {0}, how are you?", new object[] { num });

How to change property value that having new C# 6.0 string interpolation to new referenced value?

Firstly, your current code relies on the intalization order of your class, luckily it's the right order, but that is an implementation detail and may change

Secondly, the following property, is an auto-implemented property, you can think of it just like setting it in the constructor, it's never re-evaluated again

public static string DateFormat24H { get; set; } = $"yyyy{separator}MM/dd HH:mm:ss";

Lastly, What you are most likely looking for is a expression body definition to implement a read-only property. Which would look like this.

public static string DateFormat24H => $"yyyy{separator}MM/dd HH:mm:ss";

Every time you call it, it will reevaluate the interpolation

Update

you see your Lastly, post. please can you gave full example of using
get; set; both so evaluating the separator. and set the property. i
mean using backing field or something like screenshot. prnt.sc/q22q0r
Please execuse me about that.

You can't do this with interpolation, you need to use String.Format
Example of settable property

private static string _separator = "/";

private static string _backing = "yyyy{0}MM/dd HH:mm:ss";

public static string DateFormat24H
{
get => string.Format(_backing, _separator);
set => _backing = value;
}

Usage

Console.WriteLine(DateFormat24H);
_separator = "@";
Console.WriteLine(DateFormat24H);
DateFormat24H = "yyyyMM{0}dd";
Console.WriteLine(DateFormat24H);

Output

yyyy/MM/dd HH:mm:ss
yyyy@MM/dd HH:mm:ss
yyyyMM@dd

Long string interpolation lines in C#6 don't support Tab,CR and LF

You have the verbatim modifier @ in front of that string, so your tab characters will be un-escaped and treated as normal text. If you want to include them in the string, then you can either enclose the characters in curley brackets (since you're also using the $ string interpolation modifier) so they're treated as tabs (same with the carriage return and newline characters):

    var name = "myname";
var text = $@"{"\t\t"}{name}
tab and name is in a Long string interpolation {"\r\n"}
";
Console.WriteLine(text);

Alternatively, since it's a verbatim string, you can just press Tab (or Enter) keys where you want those characters in the string.

This string is the same as the one above:

    var text = $@"      {name}
tab and name is in a Long string interpolation

";

C# 6.0, .NET 4.51 and VS2015 - Why does string interpolation work?

As mentioned in the comments, string interpolation works in this case as all the new compiler does is convert the expression into an "equivalent string.Format call" at compile time.

From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with traditional format strings) and doesn’t introduce any post compile injection of code via strings.


The FormattableString is a new class allows you to inspect the string interpolation before rendering so you can check the values and protect against injection attacks.

// this does not require .NET 4.6
DateTime now = DateTime.Now;
string s = $"Hour is {now.Hour}";
Console.WriteLine(s);

//Output: Hour is 13

// this requires >= .NET 4.6
FormattableString fs = $"Hour is {now.Hour}";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.GetArgument(0));

//Output: Hour is {0}
//13


Related Topics



Leave a reply



Submit