The Self-Taught Programmer

Recipes from real-world experience with asp.net.

Archive for the ‘Common Function Library Methods’ Category

Common Function Library – HasValue()

with one comment

Like many programmers, I have a Common Function Library containing generic methods I use over and over again. Here is one of them.

/// <summary>
/// Checks a variable to make sure it has value (isn't null or a zero-length string once trimmed).
/// </summary>
/// <param name="o">variable to test.</param>
/// <returns>true if the variable has a value.</returns>
public static bool HasValue(object o)
{
	if ( o == null )
	{
		return false;
	}

	if ( o == System.DBNull.Value )
	{
		return false;
	}

	if ( o is String )
	{
		if ( ( (String)o ).Trim() == String.Empty )
		{
			return false;
		}
	}

	return true;
}

I use this often to test if a variable or object exists and if it has any value. This is an easy way to avoid NullReferenceExceptions or other errors that would crop up if an object is null — BEFORE the exception is thrown.

Advertisements

Written by Jim McMullen

May 12, 2011 at 1:24 am