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