Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoidable boxing in string interpolation

Using string interpolation makes my string format looks much more clear, however I have to add .ToString() calls if my data is a value type.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var person = new Person { Name = "Tom", Age = 10 };
var displayText = $"Name: {person.Name}, Age: {person.Age.ToString()}";

The .ToString() makes the format longer and uglier. I tried to get rid of it, but string.Format is a built-in static method and I can't inject it. Do you have any ideas about this? And since string interpolation is a syntax sugar of string.Format, why don't they add .ToString() calls when generating the code behind the syntax sugar? I think it's doable.

like image 614
Cheng Chen Avatar asked Oct 18 '22 16:10

Cheng Chen


1 Answers

I do not see how you can avoid that boxing by compiler. Behavior of string.Format is not part of C# specification. You can not rely on that it will call Object.ToString(). In fact it does not:

using System;
public static class Test {
    public struct ValueType : IFormattable {
        public override string ToString() => "Object.ToString";
        public string ToString(string format, IFormatProvider formatProvider) => "IFormattable.ToString";
    }
    public static void Main() {
        ValueType vt = new ValueType();
        Console.WriteLine($"{vt}");
        Console.WriteLine($"{vt.ToString()}");
    }
}
like image 145
user4003407 Avatar answered Oct 21 '22 06:10

user4003407