The Throbbing Brain

Technology musings for the modern pragmatist

system.nullable vs. Tryparse

I’ve been working on some code tonight and needed to use the trusty struct.TryParse methods available in the core framework.  Unfortunately, the built in TryParse methods choke on nullable types.  After a frightfully short google search I ran across a blog entry from Steve Michelotti describing his approach to writing his own TryParse object for nullable types.  Its pretty sweet though it didn’t meet a specific need that I had, specifically the ability to have the result parameter have its value set to null in cases where the string passed in is in fact null (or empty).

I’ve modified his basic concept with an overloaded method that allows you to specify how the result parameter value will be set.  Passing true to the alwaysNull parameter will always set your value to null if the string sent to the function is null or empty (which is what I’m using for my code problem).  Conversely, passing false will result in the default behavior expected from the TryParse methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static class NullableParser {
    private delegate bool TryParseDelegate(string s, out T result) where T : struct;
    private static bool TryParseNullable(string value, out Nullable result, TryParseDelegate tryParse, bool alwaysNull) where T : struct {
        if(string.IsNullOrEmpty(value)) {
            if(alwaysNull) {
                result = null;
                return false;
            } else {
                result = default(T);
                return false;
            }
        }
        T tempResult;
        bool success = tryParse(value, out tempResult);
        result = tempResult;
        return success;
    }

    public static bool TryParse(string value, out DateTime? result, bool alwaysNull) {
        return TryParseNullable(value, out result, DateTime.TryParse, alwaysNull);
    }
    public static bool TryParse(string value, out DateTime? result) {
        return NullableParser.TryParse(value, out result, false);
    }
}

Clearly this needs to have the rest of the native value type methods completed, i.e. TryParseInt, TryParseDouble, TryParseBoolean, etc. though it illustrates the basic concept well.

Update

Take a look at system.nullable vs. tryparse revisited for a fully implemented Null Parser.

Comments