Object - ToNullableGuid
An object extension method that converts the @this to a nullable unique identifier.
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); } } }
View Source
using System; public static partial class Extensions { /// <summary> /// An object extension method that converts the @this to a nullable unique identifier. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a Guid?</returns> public static Guid? ToNullableGuid(this object @this) { if (@this == null || @this == DBNull.Value) { return null; } return new Guid(@this.ToString()); } }