Blog

posts from 2020

C# boxing with string concatenation and interpolation

5 Comments
By Fons Sonnemans, 10-jan-2020

C# boxing with String concatenation and interpolation

Boxing is evil and you should always try to avoid it. That is what I tell my students in my C# training. But what is boxing and how do you avoid it. Boxing is wrapping a value type (struct) inside a reference type (object or interface) variable.

using System;

namespace BoxingDemo {
    class Program {
        static void Main(string[] args) {
            int a = 5;
            object b = a;      // boxing
            IComparable c = a; // boxing
            int d = (int)b;    // unboxing, also evil (slow)
        }
    }
}

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”). I will first explain how you can detect boxing and then how to avoid it when using string concatenation and interpolation.

READ MORE

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.