Object - ToLong

An object extension method that converts the @this to an long.

Try it

public static void Main()
{
    object[] values = { true, -12, 163, 935, 'x', new DateTime(2009, 5, 12),
            "104", "103.0", "-1",
            "1.00e2", "One", 1.00e2, 16.3e42};
    long result;

    foreach (object value in values)
    {
        try
        {
			//C# Extension Method: Object - ToLong
            result = value.ToLong();
            Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                              value.GetType().Name, value,
                              result.GetType().Name, result);
        }
        catch (OverflowException)
        {
            Console.WriteLine("The {0} value {1} is outside the range of the long type.",
                              value.GetType().Name, value);
        }
        catch (FormatException)
        {
            Console.WriteLine("The {0} value {1} is not in a recognizable format.",
                              value.GetType().Name, value);
        }
        catch (InvalidCastException)
        {
            Console.WriteLine("No conversion to an long exists for the {0} value {1}.",
                              value.GetType().Name, value);

        }
    }
}

View Source
using System;

public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to a long.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a long.</returns>
    public static long ToLong(this object @this)
    {
        return Convert.ToInt64(@this);
    }
}