Convert a boxed integer to an nullable integer with potentially different type Given a boxed integer (with a boxed short, int, ...) I want to convert it to an unboxed, nullable type instead. It should be possible to convert non-matching types (for example: boxed int to short?) Can you please comment on:

using System;

public class Test
{
    public static void Main()
    {
        int? x = Unbox&lt;int&gt;((short)42);
        short? y = Unbox&lt;short&gt;(42);
    }

    static T? Unbox&lt;T&gt;(object x) where T : struct
    {
        return typeof(T) == x.GetType() ? (T)x : (T)Convert.ChangeType(x, typeof(T));
    }
}
You should probably add IConvertible restriction on T, since it is used by Convert.ChangeType method.

Also this check: typeof(T) == x.GetType() looks like an overhead. Convert.ChangeType does nothing if types match. For example, check out Int32 sources:

int IConvertible.ToInt32(IFormatProvider provider) {
    return m_value;
}


So you might as well just check for null instead:

static T? Unbox&lt;T&gt;(object x) where T : struct, IConvertible
{
    if (x == null) return null;
    return (T)Convert.ChangeType(x, typeof(T));
}


Edit: as mentioned by sir t3chb0t, there are cases, where Convert.ChangeType can throw. So it might be a good idea to swallow exceptions inside your method and return null in those cases. But it also can be a very bad idea. It depends on use case, which you should carefully evaluate.