How to test whether a value is boxed in C# / .NET?

Try the following

public static bool IsBoxed<T>(T value)
{
    return 
        (typeof(T).IsInterface || typeof(T) == typeof(object)) &&
        value != null &&
        value.GetType().IsValueType;
}

By using a generic we allow the function to take into account both the type of the expression as viewed by the compiler and it’s underlying value.

Console.WriteLine(IsBoxed(42));  // False
Console.WriteLine(IsBoxed((object)42)); // True
Console.WriteLine(IsBoxed((IComparable)42));  // True

EDIT

A couple of people have asked for clarification on why this needs to be generic. And questioned why this is even needed at all, can’t the developer just look at code and tell if a value is boxed? In an attempt to answer both those questions consider the following method signature

void Example<T>(T param1, object param2, ISomething param3) where T : ISomething {
  object local1 = param1;
  ISomething local2 = param1;
  ...
}

In this scenario any of the provided parameters or locals could potentially represent boxed values and could just as easily not be. It’s impossible to tell by casual inspection, only an examination of a combination of the runtime type and the reference by which the value is held can determine that.

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş