Skip to content

String interpolation can cause boxing which can be avoided using ToString() #16618

@sonnemaf

Description

@sonnemaf

The following code causes boxing of the 'salary' value type.

double salary = 1200;
string text = $"Salary {salary:C2}";
Console.WriteLine(text);

Boxing is evil because it is “slow”. It creates a reference type (the boxed value) which the garbage collector has to clean up (which is also “slow”). You can easily do this by adding a ToString().

double salary = 1200;
string text = $"Salary {salary.ToString("C2")}";
Console.WriteLine(text);

I think this should be mentioned in the docs.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions