Object - ToChar

An object extension method that converts the @this to a character.

Try it

public static void Main()
{
    object[] values = { 'r', "s", "word", (byte) 83, 77, 109324, 335812911,
            new DateTime(2009, 3, 10), (uint) 1934,
            (sbyte) -17, 169.34, 175.6m, null };

    foreach (object value in values)
    {
        try
        {
			//C# Extension Method: Object - ToChar
            char result = value.ToChar();
            Console.WriteLine("The {0} value {1} converts to {2}.",
                              value.GetType().Name, value, result);
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
        catch (InvalidCastException)
        {
            Console.WriteLine("Conversion of the {0} value {1} to a Char is not supported.",
                              value.GetType().Name, value);
        }
        catch (OverflowException)
        {
            Console.WriteLine("The {0} value {1} is outside the range of the Char data type.",
                              value.GetType().Name, value);
        }
        catch (NullReferenceException)
        {
            Console.WriteLine("Cannot convert a null reference to a Char.");
        }
    }
}

View Source
using System;

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