Get the App
SLTechnology News&Howtos  ›  Development  › 

.net 6 how to use constant interpolation string

Shulou Source: shulou.com Published: 2022-06-01 05:57:20 10月02日 Update

This article mainly introduces. NET 6 constant interpolation string how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this .NET 6 constant interpolation string article will have something to gain, let's take a look.

The code is as follows:

String scheme = "https"; string host = "xxx.com"; int port = 8080th Console.WriteLine (string.Format ("{0}: / / {1}: {2}", scheme, host, port))

However, this replacement method is prone to errors, such as wrong parameter order, invalid index numbers and so on.

Therefore, the recommended way to write is to use string interpolation, with the following code:

Console.WriteLine ($"{scheme}: / / {host}: {port}")

This makes it easier to read, and the value of the variable is replaced directly into the string.

Constant interpolation string

When all strings are constant, before .NET 6, you cannot use string interpolation, just use + concatenation strings:

In .NET 6, we can already use interpolated strings for constants, as follows:

Const string FirstName = "My"; const string LastName = "IO"; const string FullName = $"{FirstName} {LastName}"

It is important to note that constants in an interpolated string cannot be numbers:

This is because there is a culture distinction when converting numeric constants to strings, which can only be obtained at run time:

Console.WriteLine ($"{1234.56}"); / / output: 1234.56 Thread.CurrentThread.CurrentCulture= new CultureInfo ("es-ES"); Console.WriteLine ($"{1234.56}"); / / output: 1234. Conclusion:

When using parameters for Attribute, constant interpolation of strings is very convenient, as shown in the following code:

Public class xxClass {[Obsolete ($"Use {nameof (NewMethod)} instead")] public void OldMethod () {} public void NewMethod () {}}

In this way, we don't have to hard-code the method name in Message.

This is the end of the article on "how to use .NET 6 constant interpolation strings". Thank you for reading! I believe that everyone has a certain understanding of the ".NET 6 constant interpolation string how to use" knowledge, if you want to learn more knowledge, welcome to follow the industry information channel.

Tags: Characters strings constants interpolation codes numbers knowledge content regions cultures parameters articles no value writing variables but only names easy to operate Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker Microsoft OPPO Reno Shulou Information