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

No Comments