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.
Pingback: How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist « The Self-Taught Programmer