HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Convert a boxed integer to an nullable integer with potentially different type

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertwithboxedtypenullabledifferentpotentiallyinteger

Problem

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((short)42);
        short? y = Unbox(42);
    }

    static T? Unbox(object x) where T : struct
    {
        return typeof(T) == x.GetType() ? (T)x : (T)Convert.ChangeType(x, typeof(T));
    }
}

Solution

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(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.

Code Snippets

int IConvertible.ToInt32(IFormatProvider provider) {
    return m_value;
}
static T? Unbox<T>(object x) where T : struct, IConvertible
{
    if (x == null) return null;
    return (T)Convert.ChangeType(x, typeof(T));
}

Context

StackExchange Code Review Q#152246, answer score: 16

Revisions (0)

No revisions yet.