/// <summary> /// Tries to convert the specified object to a string. Uses custom type converters if available. /// Returns null for a null object. /// </summary> /// <param name="o"></param> /// <returns></returns> public static string ConvertToString(object o) { if (o == null) { return(null); } // Get the type converter if available if (o.GetType().IsEnum) { var enumConverter = new EnumStringValueTypeConverter(); return((string)enumConverter.ConvertTo(o, typeof(string))); } return(o.ToString()); }
public void DirectOperationTest() { var converter = new EnumStringValueTypeConverter(); // Check source type Assert.IsTrue(converter.CanConvertFrom(typeof(Enum))); Assert.IsTrue(converter.CanConvertFrom(typeof(MockEnum))); Assert.IsTrue(converter.CanConvertFrom(typeof(MockEnum?))); Assert.IsFalse(converter.CanConvertFrom(typeof(Boolean))); Assert.IsFalse(converter.CanConvertFrom(typeof(EnumStringValueTypeConverter))); // Check destination type Assert.IsTrue(converter.CanConvertTo(typeof(string))); Assert.IsFalse(converter.CanConvertTo(typeof(Boolean))); Assert.IsFalse(converter.CanConvertTo(typeof(EnumStringValueTypeConverter))); // Check conversion Assert.AreEqual("FooBar", converter.ConvertTo(MockEnum.TestA, typeof(string))); Assert.AreEqual("3.14159265358979323846", converter.ConvertTo(MockEnum.TestB, typeof(string))); Assert.AreEqual("TestC", converter.ConvertTo(MockEnum.TestC, typeof(string))); MockEnum? nullable = MockEnum.TestB; Assert.AreEqual("3.14159265358979323846", converter.ConvertTo(nullable, typeof(string))); }