by Dominic Zukiewicz
1. July 2008 15:50
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:
- When the parameter is null, the exception message states "Parameter is null.";
- 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 ?
92e993a8-0fab-4b0a-9fc4-4ef09293acb8|0|.0
Tags:
Framework