DEV Community

Anastasiia Ogneva
Anastasiia Ogneva

Posted on

Does C# always have boxing with string concatenation and interpolation?

The C# developers are familiar with the term "boxing". It can be either obvious or unnoticeable. For example, the addition of a value type and string can cause boxing. Or not. Something like "Schrödinger's boxing". Here we try to deal with this uncertainty.

Image description

How we faced it

This topic did not appear out of thin air. The point is that I am a C# developer of the PVS-Studio static code analyzer. In 2023, as one of the development directions, we chose diagnostic rules for Unity Engine projects. In particular, we decided to implement diagnostics to indicate optimization opportunities.

We started with the diagnostic rule V4001. This rule defines the code that is executed quite often and points to the boxing inside it. Boxing is a computationally expensive process compared to passing by reference or value. That's why we decided to implement the functionality of searching for its use cases.

One of the cases that we considered was the boxing with string and value concatenation:
_
string Foo(int a)
{
return "The value is " + a;
}
_

It seems that boxing is always here. But as we delved deeper, we understood that nothing was so obvious.

You can read the continuation of this interesting project here. We look forward to your feedback!

Top comments (0)