C# Extension Method: Object - ToNullableSingle

CSharp · Console

/Program.cs

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

// @nuget: Z.ExtensionMethods

using System;
					
public class Program
{
	public static void Main()
	{
        object[] values = { true, null, 'a', 123, 1.764e32, "9.78", "1e-02",
                1.67e03, "A100", "1,033.67", DateTime.Now,
                Decimal.MaxValue, Double.MaxValue };
        float? result;

        foreach (object value in values)
        {
            try
            {
				//C# Extension Method: Object - ToNullableSingle
                result = value.ToNullableSingle();
                Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.",
                                  value == null ? "null" : value.GetType().Name,
								  value == null ? "null" : value,
								  result == null ? "null" : result.GetType().Name,
								  result == null ? "null" : result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("The {0} value {1} is not recognized as a valid float value.",
                                  value == null ? "null" : value.GetType().Name, value);
            }
            catch (OverflowException)
            {
                Console.WriteLine("The {0} value {1} is outside the range of the float type.",
                                  value == null ? "null" : value.GetType().Name, value);
            }
            catch (InvalidCastException)
            {
                Console.WriteLine("Conversion of the {0} value {1} to a float is not supported.",
                                  value == null ? "null" : value.GetType().Name, value);
            }
        }
	}
}
;