C# Extension Method: Object - ToNullableChar

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002502/object-tonullablechar

// @nuget: Z.ExtensionMethods

using System;
					
public class Program
{
	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 - ToNullableChar
                char? result = value.ToNullableChar();
                Console.WriteLine("The {0} value {1} converts to {2}.",
                                  value != null ? value.GetType().Name : "null", 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.");
            }
        }
	}
}
;