January 3, 2007

.NET Nuggets

With all the flashy new features of ASP.NET 2.0 it's easy to overlook the little things that actually help out in your daily coding. Here's a couple that I use quite often:

  1. String.IsNullOrEmpty(string value)

    This method does exactly what it says, returns true if a given string is either null or empty. A quick look in reflector reveals that it does this by properly checking the length of the string as opposed to comparing it to String.Empty:



    public static bool IsNullOrEmpty(string value)
    {
    if (value != null)
    {
    return (value.Length == 0);
    }
    return true;
    }


  2. int.TryParse(string s, out int result)

    This method takes a string and attempts to convert it to an integer, returning the result through an output parameter. If the conversion is successful, the result will be the appropriate integer, otherwise the result will be zero. The conversion will fail if the input parameter is null, not a properly formatted integer, or falls outside the range of an Int32 type.


    I looked at this with Reflector, and it's a bit too complicated to post here, but the cool thing is that it does it's thing without ever using a try/catch. This method definitely comes in handy when you need to get integer values from an untrusted source like the querystring.