Object - ToNullableByteOrDefault
An object extension method that converts this object to a nullable byte or default.
public static void Main() { object val1 = true; object val2 = 8; object thisNull = null; object thisInvalid = "FizzBuzz"; string format = "{0, -20} {1, -15}"; Console.WriteLine(format, "Object", "ToNullableByteOrDefault"); Console.WriteLine(format, "------", "-----------------------"); // C# Extension Method: Object - ToNullableByteOrDefault Console.WriteLine(format, val1, val1.ToNullableByteOrDefault()); Console.WriteLine(format, val2, val2.ToNullableByteOrDefault()); Console.WriteLine(format, "null", thisNull.ToNullableByteOrDefault()); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableByteOrDefault()); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableByteOrDefault(0)); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableByteOrDefault(() => 0)); }
View Source
using System; public static partial class Extensions { /// <summary> /// An object extension method that converts this object to a nullable byte or default. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>The given data converted to a byte?</returns> public static byte? ToNullableByteOrDefault(this object @this) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToByte(@this); } catch (Exception) { return default(byte); } } /// <summary> /// An object extension method that converts this object to a nullable byte or default. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The given data converted to a byte?</returns> public static byte? ToNullableByteOrDefault(this object @this, byte? defaultValue) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToByte(@this); } catch (Exception) { return defaultValue; } } /// <summary> /// An object extension method that converts this object to a nullable byte or default. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="defaultValueFactory">The default value factory.</param> /// <returns>The given data converted to a byte?</returns> public static byte? ToNullableByteOrDefault(this object @this, Func<byte?> defaultValueFactory) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToByte(@this); } catch (Exception) { return defaultValueFactory(); } } }