Back To Basics - Thinking Beyond ToString()

By Anoop Madhusudanan

Vote on HN

About Back To Basics - It's often good to look back and fill any gaps we might be having, in certain aspects of the language or framework we use. I'll be examining and blogging about some well known features of C# and .NET, in Back To Basics series - Probably in a bit more detail.

If you want to convert something to string, you might need to find the converter to do the job correctly.

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 = 

            // 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 is the result
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.

1 comment:

  1. dear author

    i read your blog
    thank for it

    & Send me informationn & your article link for MVC


Please keep your comments clean.

© 2012. All Rights Reserved.