Matt Dawdy Matt Dawdy - 14 days ago 6
C# Question

Helper functions for safe conversion from strings

Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0.

I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all.

So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure.

I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about.

Then I'd do this for strings. And Dates.

Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.

Answer

There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception.

Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type:

public static T SafeConvert<T>(string s, T defaultValue)
{
    if ( string.IsNullOrEmpty(s) )
        return defaultValue;
    return (T)Convert.ChangeType(s, typeof(T));
}

Use:

SafeConvert(null, 0.0) == 0.0;
SafeConvert("", 0.0) == 0.0;
SafeConvert("0", 0.0) == 0.0;

This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass 0 and you'd get an In32 back. Pass 0L, Int64. And so on...

Comments