A simple string to valuetype converter using TypeDescriptor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are the tests written for this class.