If you want to convert something to string
, what is the best way?.
Here is a neat extension method for all your objects, so that it'll find the appropriate converter if one exists, or otherwise, fall back to ToString()
. :)
public static class ConverterExtension
{
public static string ConvertToString(this object value)
{
TypeConverter converter =
TypeDescriptor.GetConverter(value.GetType());
if (converter.CanConvertTo(typeof(string)))
{
return converter.ConvertTo(value,
typeof(string)) as string;
}
return value.ToString();
}
}
Now, try this code, and find out what the result is:
Color val = Color.Red;
string result1 = val.ConvertToString();
string result2=val.ToString();
See what is in result1
and result2
, so that you can make out what I'm talking about. Simple, but useful when you work with scenarios where you want to serialize your object's properties.
CodeProject
Architect, Developer, Speaker | Wannabe GUT inventor & Data Scientist | Microsoft MVP in C#