Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#

Thinking Beyond ToString()

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Oct 2009CPOL 7.9K   4  
Thinking beyond ToString()

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(). :)

C#
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();
        }
    }

Now, try this code, and find out what the result is:

C#
Color val = Color.Red;

//Call our extension method
string result1 = val.ConvertToString();

//Try with ToString()
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.

This article was originally posted at http://amazedsaint.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Architect, Developer, Speaker | Wannabe GUT inventor & Data Scientist | Microsoft MVP in C#

Comments and Discussions

 
-- There are no messages in this forum --