TryParse Extension Methods

TryParse Extension Methods

When .NET 2.0 was released, a TryParse() method was added to many value types such as Int32, DataTime, etc. This was a huge improvement because there was no longer a need to catch expensive exceptions and drag down performance. However, one drawback of the TryParse() method is that the syntax is a little clunky. The most common example looks like this:

1: Person person = new Person();

2: string value = "21";

3: int num;

4: int.TryParse(value, out num);

5: person.Age = num;

So it's great that we can do all this without having to catch exceptions but it definitely seems more complex than it has to be given that all we're trying to do is assign an integer to the Age property and we need this many lines of code.  We can use Extension methods to make the consuming code much more friendly - a single line of code:

1: person.Age = value.TryParseInt32();

To implement the static class for the extension methods, we *could* implement each TryParseXX() method like this:

1: public static int TryParseInt32(this string value)

2: {

3: int result;

4: int.TryParse(value, out result);

5: return result;

6: }

However, now we've got the ugly, repetitive code in numerous methods inside that class. On the good side, at least we've encapsulated the repetitive code inside a single class, but we can leverage a generic delegate and generic method to even avoid the repetition inside that class.

1: private delegate bool ParseDelegate(string s, out T result);

2:  

3: private static T TryParse(this string value, ParseDelegate parse) where T : struct

4: {

5: T result;

6: parse(value, out result);

7: return result;

8: }

This allows our TryParseInt32() implementation to now be a single line of code:

1: public static int TryParseInt32(this string value)

2: {

3: return TryParse<int>(value, int.TryParse);

4: }

The ParseDelegate is generic that matches the signature of all the TryParse() methods. So we can imply pass in the int.TryParse delegate and it will be executed *inside* the re-useable TryParse method that I have created.  This utility class can be used in all kinds of different string parsing situations.  Here is the complete code for the TryParseExtensions class:

1: public static class TryParseExtensions

2: {

3:

4: public static int TryParseInt32(this string value)

5: {

6: return TryParse<int>(value, int.TryParse);

7: }

8:  

9: public static Int16 TryParseInt16(this string value)

10: {

11: return TryParse(value, Int16.TryParse);

12: }

13:  

14: public static Int64 TryParseInt64(this string value)

15: {

16: return TryParse(value, Int64.TryParse);

17: }

18:  

19: public static byte TryParseByte(this string value)

20: {

21: return TryParse<byte>(value, byte.TryParse);

22: }

23:  

24: public static bool TryParseBoolean(this string value)

25: {

26: return TryParse<bool>(value, bool.TryParse);

27: }

28:  

29: public static Single TryParseSingle(this string value)

30: {

31: return TryParse(value, Single.TryParse);

32: }

33:  

34: public static Double TryParseDoube(this string value)

35: {

36: return TryParse(value, Double.TryParse);

37: }

38:  

39: public static Decimal TryParseDecimal(this string value)

40: {

41: return TryParse(value, Decimal.TryParse);

42: }

43:  

44: public static DateTime TryParseDateTime(this string value)

45: {

46: return TryParse(value, DateTime.TryParse);

47: }

48:  

49: #region Private Members

50:  

51: private delegate bool ParseDelegate(string s, out T result);

52:  

53: private static T TryParse(this string value, ParseDelegate parse) where T : struct

54: {

55: T result;

56: parse(value, out result);

57: return result;

58: }

59:  

60: #endregion

61:  

62: }

posted on Sunday, October 5, 2008 5:30 PM Print

This article is part of the GWB Archives. Original Author: Steve Michelotti

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.