Object - ToNullableShortOrDefault
An object extension method that converts this object to a nullable short or default.
public static void Main() { object val1 = 123; object val2 = "1090"; object thisInvalid = "A100"; object thisNull = null; string format = "{0, -30} {1, -15}"; Console.WriteLine(format, "Object", "ToNullableShortOrDefault"); Console.WriteLine(format, "------", "------------------------"); // C# Extension Method: Object - ToNullableShortOrDefault Console.WriteLine(format, val1, val1.ToNullableShortOrDefault()); Console.WriteLine(format, val2, val2.ToNullableShortOrDefault()); Console.WriteLine(format, "null", thisNull.ToNullableShortOrDefault()); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableShortOrDefault()); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableShortOrDefault(-1)); Console.WriteLine(format, thisInvalid, thisInvalid.ToNullableShortOrDefault(() => -2)); }
View Source
using System; public static partial class Extensions { /// <summary> /// An object extension method that converts this object to a nullable short or default. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>The given data converted to a short?</returns> public static short? ToNullableShortOrDefault(this object @this) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToInt16(@this); } catch (Exception) { return default(short); } } /// <summary> /// An object extension method that converts this object to a nullable short 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 short?</returns> public static short? ToNullableShortOrDefault(this object @this, short? defaultValue) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToInt16(@this); } catch (Exception) { return defaultValue; } } /// <summary> /// An object extension method that converts this object to a nullable short 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 short?</returns> public static short? ToNullableShortOrDefault(this object @this, Func<short?> defaultValueFactory) { try { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToInt16(@this); } catch (Exception) { return defaultValueFactory(); } } }