TryParse and Generics...Awesome!

Here's a fantastic way to write a generic method that will TryParse any struct that implements this type check. I hate writing the same three lines of code over and over to try and parse a value...so, here's a way of doing it. I placed this method into a helper class that contains helper APIs.

 

public delegate bool ParseDelegate<T>(string value, out T result);
public static T TryParse<T>(string value, ParseDelegate<T> parse) where T : struct
{
    T result;
    parse(value, out result);
    return result;
}

 

I will give credit where credit is due... I found this little ditty on Steve Michelotti's blog:

http://geekswithblogs.net/michelotti/Default.aspx

 

Good stuff Steve!!

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.