Object - ToNullableSByte

An object extension method that converts the @this to a nullable s byte.

Try it

public static void Main()
{
    object[] values = { true, null, -12, 163, 935, 'x', "104", "103.0", "-1",
            "1.00e2", "One", 1.00e2};
    sbyte? result;

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

        }
    }
}

View Source
using System;

public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to a nullable s byte.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a sbyte?</returns>
    public static sbyte? ToNullableSByte(this object @this)
    {
        if (@this == null || @this == DBNull.Value)
        {
            return null;
        }

        return Convert.ToSByte(@this);
    }
}