Why use interpolated strings instead string.format

Time:2020-11-28

If you know why you want to use an interpolated string, only those who have stepped on the pit can understand it. If you have ever used it string.format There are more than 5 placeholders. I think you can resonate with the pain.

1: Painful experience

First of all, we have written a piece of code. Let’s have a look at it

LogHelper.WriteLog ( string.Format (@ "= = = = = = = [step 4] the leaflet is sent successfully. marketID={0}, 
                                       Marketname = {1}, total customers: {2}, success: {3}, failure: {4}, repetition: {5},
                                       Current priority: {6}, shopid = {7} ",
                                      leafletEntity.MarketingID, leafletEntity.MarketingName, 
                                      leafletEntity.CustomerList.Count,leafletEntity.SuccessCount,
                                      leafletEntity.FailCount, leafletEntity.RepeatCustomerNum, 
                                      leafletEntity.Priority, leafletEntity.ShopID));

There are as many as eight placeholders here. When I wrote this, there were three pain points.

1. The place holder cannot be written wrong

For example, here {0}, {1}, {2}… Cannot be written as {0}, {0}, {2}, resulting in repeated output of results.

Why use interpolated strings instead string.format

2. The number of parameter values cannot be more or less

Take the last leafletEntity.ShopID If the parameter value is lost, there will be 8 place holders and 7 parameters, which will cause the system to throw an exception.
Why use interpolated strings instead string.format

3. The sequence of parameter values cannot be wrong

If there are too many parameter values, it is difficult to ensure that the order is not wrong, such as here leafletEntity.FailCount and leafletEntity.RepeatCustomerNum , reversed to leafletEntity.RepeatCustomerNum and leafletEntity.FailCount Can you see it at a glance???
Why use interpolated strings instead string.format

2: Solutions

string.format It is also a historical legacy of imitating C language. Now C ා 6.0 comes out with this interpolation string, which perfectly solves these three problems. It’s not too exciting. Next, change the beginning of the article to the interpolation version.

LogHelper.WriteLog ([email protected] "= = = = = = [step 4] the leaflet is sent successfully. 
                                  marketID={leafletEntity.MarketingID}, 
                                  marketName={leafletEntity.MarketingName}, 
                                  Total customers:{ leafletEntity.CustomerList.Count }
                                  Success:{ leafletEntity.SuccessCount }People, 
                                  Failed:{ leafletEntity.FailCount }People,
                                  Repeat:{ leafletEntity.RepeatCustomerNum }People,
                                  Current priority:{ leafletEntity.Priority }
                                  Shopid={ leafletEntity.ShopID }");

Interpolation string method is just to add “$” before the string, give you time to have a careful taste, is it a good solution to the three pain points I mentioned before.

1. The use of ternary operator interpolation

Most of the time, in business development, it is not only to fill in a variable, but also to support some expression values, such as the most used ternary operator

<1> Wrong usage

If you write this directly, you can’t pass a vicious compiler, such as the following.

Why use interpolated strings instead string.format

<2> Proper use

The solution can also be simple by adding a () to the periphery.
Why use interpolated strings instead string.format

2. Interpolation of complex logic

If you have complex business logic, it is recommended to start a separate approach.

    class Program
    {
        static void Main(string[] args)
        {
            var num = 10;

            var info = $"i={GetNum(num)}";
        }

        public static int GetNum(int num)
        {
            return num == 10 ? 1 : 2;
        }
    }

How your business logic is relatively simple, can be implemented in the way of inline delegation.

Why use interpolated strings instead string.format

3: Principles of inquiry

Next, let’s explore what the syntax sugar interpolation string is at the IL level. You can view the IL code through the ilspy tool.
Why use interpolated strings instead string.format

From the above screenshot, in fact, the so-called “interpolation string” is string.format The syntax sugar of the compiler

Note:

Because there is a box operation, so you have to be a snack if Console.WriteLine There will be a certain performance loss when executing multiple times. It is recommended to do box operation in advance, such as the following.

        static void Main(string[] args)
        {
            int i = 1, j = 2, k = 3;

            var it = i.ToString();
            var jt = j.ToString();
            var kt = k.ToString();

            for (int m = 0; m < int.MaxValue; m++)
            {
                Console.WriteLine($"i={it},j={jt},k={kt}");
            }
        }

Well, that’s all for this article. I hope it can help you.