Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Created February 18, 2011 14:19
Show Gist options
  • Save jakejscott/833703 to your computer and use it in GitHub Desktop.
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
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