Object - ToNullableBoolean
An object extension method that converts the @this to a nullable boolean.
public static void Main() { string format = "{0, -49} {1, -15}"; object[] values = { null, 16.33, -24, 0, "12", "12.7", String.Empty, "1String", "True", "false", new System.Collections.ArrayList() }; Console.WriteLine(format, "Object", "ToNullableBoolean"); Console.WriteLine(format, "------", "-----------------"); foreach(var val in values) { Console.Write("{0,-50}", val != null ? String.Format("{0} ({1})", val, val.GetType().Name) : "null"); try { // C# Extension Method: Object - ToNullableBoolean bool? result = val.ToNullableBoolean(); Console.WriteLine("{0}", result); } catch (FormatException) { Console.WriteLine("Bad Format"); } catch (InvalidCastException) { Console.WriteLine("No Conversion"); } } }
View Source
using System; public static partial class Extensions { /// <summary> /// An object extension method that converts the @this to a nullable boolean. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a bool?</returns> public static bool? ToNullableBoolean(this object @this) { if (@this == null || @this == DBNull.Value) { return null; } return Convert.ToBoolean(@this); } }