Converts String to Any Other Type

image_pdfimage_print
   
 
//http://sb2extensions.codeplex.com/
//Apache License 2.0 (Apache)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sb2.Extensions
{
    public static class NullableExtensions
    {
        /// <summary>
        /// Converts String to Any Other Type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The 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;
        }
        /// <summary>
        /// Converts String to Any Other Type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <param name="provider">The provider.</param>
        /// <returns></returns>
        public static T? ConvertTo<T>(this string input, IFormatProvider provider) where T : struct
        {
            T? ret = null;

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

            return ret;
        }
        public static string ToString(this char? input)
        {
            return input.HasValue ? input.Value.ToString() : String.Empty;
        }
        public static char? ToNullableChar(this string input)
        {
            if (input.Trim().Length == 0)
                return new char?();
            else if (input.Trim().Length > 1)
                throw new ArgumentException("Cannot convert string(" + input.Trim().Length + ") to char?");
            else
                return input[0];
        }
    }
}

   
     


This entry was posted in Data Types. Bookmark the permalink.