Nullable ConvertTo Extension Method

Hello,

I have the need to easily convert a string to another type i.e. int. And would like to return null if the string is empty. I created a quick extension method, thought id post it up incase anyone finds it helpful.

 

        /// <summary>
        /// Converts a string value to the given type, if the string is empty,
        /// will return null.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <returns></returns>
        public static T? ConvertTo<T>(this string input) where T : struct {
            T? ret = null;

            if (!string.IsNullOrEmpty(input)) {
                ret = (T)Convert.ChangeType(input, typeof(T));
            }

            return ret;
        }

Basically to use this, just call the extension method on a string:

 
"12".ConvertTo<int>(); // Returns 12
"".ConvertTo<int>(); // Returns null
"1ddsfs".ConvertTo<int>(); // Exception thrown (behaviour I wanted)


Just a quick one today, will be posting some more useful things in the weeks to come.



Cheers
Stefan

Published Tuesday, August 12, 2008 3:21 PM by stefan.sedich
Filed under: , , ,

Comments

# funny wallpaper &raquo; Nullable ConvertTo Extension Method

Tuesday, August 12, 2008 2:43 AM by funny wallpaper » Nullable ConvertTo Extension Method

Pingback from  funny wallpaper &raquo; Nullable ConvertTo Extension Method

# Link Listing - August 12, 2008

Wednesday, August 13, 2008 12:51 AM by Christopher Steen

WPF Podder Skinning Competition Hall of Fame [Via: Josh Smith ] Code Camps Codestock rocked! [Via:...

# Link Listing - August 12, 2008

Wednesday, August 13, 2008 12:52 AM by Christopher Steen

Link Listing - August 12, 2008

Leave a Comment

(required) 
(required) 
(optional)
(required)