Object - ToBoolean
An object extension method that converts the @this to a boolean.
public static void Main() { string format = "{0, -49} {1, -15}"; object[] values = { 16.33, -24, 0, "12", "12.7", String.Empty, "1String", "True", "false", null, new System.Collections.ArrayList() }; Console.WriteLine(format, "Object", "ToBoolean"); 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 - ToBoolean Console.WriteLine("{0}", val.ToBoolean()); } 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 boolean. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a bool.</returns> public static bool ToBoolean(this object @this) { return Convert.ToBoolean(@this); } }