The Self-Taught Programmer

Recipes from real-world experience with asp.net.

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

One Response

Subscribe to comments with RSS.

  1. […] Note that this function calls my common function library method ‘HasValue’, which can be found here. […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: