Mega Code Archive
Converts String to Any Other Type
//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
{
///
/// Converts String to Any Other Type
///
///
/// The input.
///
public static T? ConvertTo(this string input) where T : struct
{
T? ret = null;
if (!string.IsNullOrEmpty(input))
{
ret = (T)Convert.ChangeType(input, typeof(T));
}
return ret;
}
///
/// Converts String to Any Other Type
///
///
/// The input.
/// The provider.
///
public static T? ConvertTo(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];
}
}
}