Generic String.Parse Extension Method

After reading this post about missing parses method for nullable integer and possible implementation. I want to share my version of parse method with generic touch.

Here’s my parser class

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;
}
}
And here's how you use it.
// regular parsing
int i = "123".Parse<int>(); 
int? inull = "123".Parse<int?>();
DateTime d = "01/12/2008".Parse<DateTime>();
DateTime? dn = "01/12/2008".Parse<DateTime?>();

// null values string sample = null;
int? k = sample.Parse<int?>(); // returns null int l = sample.Parse<int>(); // returns 0 DateTime dd = sample.Parse<DateTime>(); // returns 01/01/0001 DateTime? ddn = sample.Parse<DateTime?>(); // returns null
Published Wednesday, March 26, 2008 9:05 PM by jigar

Comments

# re: Generic String.Parse Extension Method

Thursday, March 27, 2008 8:55 AM by AndrewSeven

I would turn that around so that the methods are defined on the appropriate types instead of adding everything to the string type. It will also be easier to add more refined versions for specific types

public static T Parse<T>(this T source,string value)

int? k = sample.Parse<int?>();

would become

int? k= Nullable<int>.Parse(...)

or to avoid needing the long form of Nullable

int? k= int.ParseNullable(...)

# re: Generic String.Parse Extension Method

Wednesday, November 26, 2008 9:20 AM by Amir

Loved it! great for loading nullable values from a XElement

# re: Generic String.Parse Extension Method

Sunday, June 21, 2009 11:49 PM by joyaspx

it's very usefull for me,thanks!

Leave a Comment

(required) 
(required) 
(optional)
(required)