TryParse for Nullable Types

TryParse for Nullable Types

In my last post, I discussed creating a static class for Parsing nullable types:

https://geekswithblogs.net/michelotti/archive/2006/01/16/66014.aspx

However, 2.0 also introducing a new TryParse pattern so that developers would not have to rely on catching exceptions when attempting a Parse method.  For example:

http://msdn2.microsoft.com/en-us/library/ch92fbc1.aspx

We can incorporate the TryParse pattern into our NullableParser class as well so that our consuming code to look something like this:

DateTime? defaultDate = DateTime.Now;

NullableParser.TryParseNullableDateTime(s, out defaultDate);

person.DateOfBirth = defaultDate;

Internally, we can implement this the same way as the ParseXXX methods by leveraging delegate inference and generics.  First define the delegate:

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

Now define the private generic method:

private static bool TryParseNullable(string s, out Nullable result, TryParseDelegate tryParse) where T: struct

{

  if (string.IsNullOrEmpty(s))

  {

    result = null;

    return true;

  }

  else

  {

    T temp;

    bool success = tryParse(s, out temp);

    result = temp;

    return success;

  }

}

Now each public method is trivial to implement:

public static bool TryParseNullableDateTime(string s, out DateTime? result)

{

  return TryParseNullable<DateTime>(s, out result, DateTime.TryParse);

}

private delegate bool TryParseDelegate(string s, out T result);

posted on Monday, January 16, 2006 6:35 AM 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.