When catering for null values, I use the ternary operator ?, which is used to do an inline IF statement. For example:

public void CheckText(string text)
{
    if(String.IsNullOrEmpty(text))
    {
        throw new ArgumentException("Parameter is " + (text==null ? "null." : "empty."));
    }
    
    //Other code here
}

This would allow you to cater for 2 exception cases:

  1. When the parameter is null, the exception message states "Parameter is null.";
  2. When the parameter is "", the exception message states "Parameter is empty.";

Since testing for null is a fairly common operation, and also catering for the possibility of a null, there is an operator called the null coalescing operator. The operator is used to check a value for null, and return an alternative value if the result is null

Before:

string text = ReadFromDB();
 
if(text == null)
    Console.WriteLine("(null)");
else
    Console.WriteLine(text);

After:

string text = ReadFromDB();
 
Console.WriteLine( text ?? "(null)" );

So, the way it works is it checks the first variable. If it is not null it returns the first variable, otherwise it returns the second. It is a shorthand method of this made up method:

public static object GetObject(object o, object _default)
{
     if( o == null )
          return _default;
     else
        return o;
 
    //Or return (o==null?_default:o);
}

The main use of this would be for outputting data to a table, or to a stream - but it looks like something I will definitely use in the future, instead of my long winded ternary operators ?


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Tuesday, July 01, 2008 4:50 PM | in Framework

Comments

No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 7 and 3 and type the answer here: