Using string interpolation and nameof in .VS 2015 NET 4.5

I use things like $"hello {person}" and nameof(arg1) in my code, but when checking the properties of a project, I am targeting .NET 4.5.

This is normal? I thought these things were introduced in 4.6.

The project builds and works on my machine, but I'm worried that something will go wrong when I breed it.

+5
source share
3 answers

This is a compiler function, not a framework function. We successfully use both functions with our .NET 3.5 projects in Visual Studio 2015.

In a nutshell, the compiler translates $"hello {person}" into String.Format("hello {0}", person) and nameof(arg1) into "arg1" . It is just syntactic sugar.

The runtime sees a call to String.Format (or the string literal "arg1", respectively) and does not know (and does not care) what the source code looked like. String.Format supported since the early days of the .NET Framework, so there is nothing stopping you from targeting an earlier version of the framework.

+11
source

Existing answers talk about this as a C # 6 function without the .NET framework component.

This fully applies to nameof , but only to some extent applies to string interpolation.

String interpolation will use string.Format in most cases, but if you are using .NET 4.6, it can also convert the interpolated string to a FormattableString , which is useful if you want invariant formatting:

 using System; using System.Globalization; using static System.FormattableString; class Test { static void Main() { CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR"); double d = 0.5; string local = $"{d}"; string invariant = Invariant($"{d}"); Console.WriteLine(local); // 0,5 Console.WriteLine(invariant); // 0.5 } } 

Obviously, this will not work if $"{d}" just called string.Format ... instead, in this case, it calls string.Format in the local assignment and calls FormattableStringFactory.Create in the invariant assignment , and calls FormattableString.Invariant on the result. If you try to compile this with an earlier version of the framework, FormattableString will not exist, so it will not compile. You can provide your own implementation of FormattableString and FormattableStringFactory if you really want to, and the compiler will use them accordingly.

+8
source

These things were introduced in C#6 . .Net has nothing to do with this. As long as you use the C # 6 compiler, you can use these functions.

What is the difference between C # and .NET?

So, yes, it’s normal to use them in targeting a .Net 4.5 project.

+1
source

Source: https://habr.com/ru/post/1240859/


All Articles