Byte byte casting

I am trying to write an extension method which, given the value, will return

  • The value itself, if it is different from DBNull.Value
  • The default value for value type

Yes, this is not the clearest explanation, maybe some code will do what I'm trying to make obvious.

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

As long as the value type in the box matches T , this method works correctly.

Real funny punches when the types are different, for example, the box value of byte and T is int .

Is there an elegant way to make this work?

Performing some type checks manually for the first transfer from, for example. object to byte , and then from byte to T , of course, won't work.

Edit

The proposed solution should also work with enumerations not only with standard types.

+6
source share
3 answers

Call your method with an argument of the type that exactly matches the value of the database, and then apply it to what you really want, for example.

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

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

  • Reading the database value into the correct equivalent .NET data type.
  • Matching the type of database access layer with the desired type of business logic level.

This separation of responsibilities becomes more important if the required data type is something even more remote from the int and requires a more complex translation, for example. enumeration, string or offset per day from the date.

+4
source
  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)); } } 
+2
source

This works for me:

 class Program { static void Main(string[] args) { Byte myByte = 5; object myObject = (object)myByte; int myInt = myObject.GetValueOrDefault<Byte>(); Console.WriteLine(myInt); // 5 myObject = DBNull.Value; myInt = myObject.GetValueOrDefault<Byte>(); Console.WriteLine(myInt); // 0 Console.ReadKey(true); } } public static class ObjectExtension { public static T GetValueOrDefault<T>(this object value) { if (value == DBNull.Value) { return default(T); } else { return (T)value; } } } 
0
source

Source: https://habr.com/ru/post/901707/


All Articles