Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Last active September 11, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendettamit/d339ee27bc76932cbfd4 to your computer and use it in GitHub Desktop.
Save vendettamit/d339ee27bc76932cbfd4 to your computer and use it in GitHub Desktop.
A simple string to valuetype converter using TypeDescriptor.
using System;
using System.ComponentModel;
namespace TestForEverything
{
/// <summary>
/// Extension methos of string providing conversions to primitve types
/// </summary>
public static class ConverterExtensions
{
/// <summary>
/// Method can be used to convert primitive types. It supports only converting IConvertible structs.
/// </summary>
/// <typeparam name="T">type for cast</typeparam>
/// <param name="value">string representation of type value</param>
/// <returns>casted value of given type</returns>
public static T To<T>(this string value) // where T: struct
{
var newType = typeof(T);
object result;
if (TryConvertTo<T>(value, out result))
{
return (T)result;
}
throw new InvalidCastException(string.Format("Unable to cast the {0} to type {1}", value, newType));
}
/// <summary>
/// Try converting by casting to special types struct like Enum, Guid and DateTime.
/// </summary>
/// <typeparam name="T">type for cast</typeparam>
/// <param name="value">string representation of type value</param>
/// <param name="result">casted value of given type</param>
/// <returns>true, if cast is successful otherwise false.</returns>
private static bool TryConvertTo<T>(this string value, out object result)
{
result = default(T);
if (string.IsNullOrWhiteSpace(value))
{
return true;
}
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
result = (T)converter.ConvertFromString(value);
return true;
}
catch(Exception exception)
{
// Log the exception if required.
// throw new InvalidCastException(string.Format("Unable to cast the {0} to type {1}", value, newType, exception));
return false;
}
}
}
}
@vendettamit
Copy link
Author

Here are the tests written for this class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment