Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting boxed byte

Tags:

c#

casting

I'm trying to write an extension method that, given a value, will return

  • The value itself if it's different from DBNull.Value
  • The default value for value's type

Yeah, that's not the clearest explanation, maybe some code will make what I'm trying to accomplish obvious.

public static T GetValueOrDefault<T>(this object value) {
    if (value == DBNull.Value)
        return default(T);
    else
        return (T)value;
}

As long as value's boxed type is the same as T, this method works correctly.

The real fun kicks in when the types are different, for instance the boxed value is byte and T is int.

Is there an elegant way to make this work?

Doing some typechecking manually to first cast from e.g. object to byte and then from byte to T, of course, won't work.

Edit

The proposed solution should work with enums too, not only with "standard" types.

like image 954
s.m. Avatar asked Nov 17 '11 11:11

s.m.


2 Answers

Call your method with a type argument that exactly matches the database value, then cast it to what you actually want, e.g.

int result = (int) row["NullableByteColumn"].GetValueOrDefault<byte>();

I think this is reasonable because the code clearly separates the two different concepts that are at work here:

  • Reading a database value into the correct equivalent .NET data type.
  • Mapping the database access layer type into the required business logic layer type.

This separation of responsibility becomes more important if the required data type is something further removed from int and requires more complex translation, e.g. an enum, a string, or a day offset from a date.

like image 57
Christian Hayter Avatar answered Oct 18 '22 01:10

Christian Hayter


    public static T GetValueOrDefault<T>(this object value) {
        if (value == DBNull.Value) {
            return default(T);
        }
        else {
            if (typeof(T).IsEnum) value = Enum.ToObject(typeof(T), Convert.ToInt64(value));
            return (T)Convert.ChangeType(value, typeof(T));
        }
    }
like image 28
Hans Passant Avatar answered Oct 18 '22 01:10

Hans Passant