Created
February 18, 2011 14:19
-
-
Save jakejscott/833703 to your computer and use it in GitHub Desktop.
String extention for converting strings to Dates etc. Assumes that you have already validated the string can covert to that type
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; | |
public static class Parser { | |
public static T Parse<T>(this string value) { | |
// Get default value for type so if string | |
// is empty then we can return default value. | |
T result = default(T); | |
if (!string.IsNullOrEmpty(value)) { | |
// we are not going to handle exception here | |
// if you need SafeParse then you should create | |
// another method specially for that. | |
TypeConverter tc = TypeDescriptor.GetConverter(typeof(T)); | |
result = (T)tc.ConvertFrom(value); | |
} return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment