first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

C# 3.0 Extension Methods: “Thinking Beyond ToString()”; Anoop Madhusudanan

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());

        // Can converter convert this type to string?
        if (converter.CanConvertTo(typeof(string)))
        {
            // Convert it
            return converter.ConvertTo(value, 
                    typeof(string)) as string;
        }

        return value.ToString();
    }
}

[http://www.codeproject.com/Articles/42820/ Thinking-Beyond-ToString.aspx?display=Print]

mod date: 2009-10-06T16:27:39.000Z