C# Extension Method: Object - ToNullableGuid

CSharp · Console

/Program.cs

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

// @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, Double.MaxValue, 
						       "ca761232ed4211cebacd00aa0057b223",
                               "CA761232-ED42-11CE-BACD-00AA0057B223", 
                               "{CA761232-ED42-11CE-BACD-00AA0057B223}", 
                               "(CA761232-ED42-11CE-BACD-00AA0057B223)", 
                               "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}"
						  };
		
        foreach (object value in values)
        {
            try
            {
				//C# Extension Method: Object - ToNullableGuid
                Guid? result = value.ToNullableGuid();
                Console.WriteLine("Converted the {0} value {1} to {2}.",
                                  value == null ? "null" : value.GetType().Name,
								  value == null ? "null" : value, 
								  result == null ? "null" : result.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("The {0} value {1} is not recognized as a valid Guid value.",
                                  value == null ? "null" : value.GetType().Name, value);
            }
            catch (InvalidCastException)
            {
                Console.WriteLine("Conversion of the {0} value {1} to a Guid is not supported.",
                                  value == null ? "null" : value.GetType().Name, value);
            }
        }
	}
}
;