Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Sep 11, 2015

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
You can’t perform that action at this time.