Common Function Library – HasValue()

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.

One thought on “Common Function Library – HasValue()

  1. Pingback: How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist « The Self-Taught Programmer

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