Correct way to boxing bool[] into object[] in C#

It sounds like you just need to box each value, right? That’s as simple as:

object[] objectArray = boolArray.Select(b => (object) b).ToArray();

Or even:

object[] objectArray = boolArray.Cast<object>().ToArray();

(As Cast will perform boxing/unboxing operations.)

Or slightly more efficiently in terms of knowing the correct size to start with:

object[] objectArray = Array.ConvertAll(boolArray, b => (object) b);

Alternatively, change your APIs to not require an object[] to start with. Consider using generic methods/types instead.

EDIT: To avoid the boxing each time, you can easily write your own extension class similar to the framework one nmclean showed:

public static class BooleanBoxExtensions
{
    private static readonly object BoxedTrue = true;
    private static readonly object BoxedFalse = false;

    public static object BoxCheaply(this bool value)
    {
        return value ? BoxedTrue : BoxedFalse;
    }
}

Then:

object[] objectArray = Array.ConvertAll(boolArray, b => b.BoxCheaply());

Or:

object[] objectArray = boolArray.Select(BooleanBoxExtensions.BoxCheaply)
                                .ToArray();

Leave a Comment