I have a new favorite feature in VS 2005 - the null coalescing operator: ??
This is a short cut for checking if a value is null and if so returning the value of the second operand. The syntax is as follows: string newVal = myVal ?? "default";
The first operand (myVal) must be a nullable type (in this case a string). This evaluates as: if myVal is not null then set newVal to the value of myVal, otherwise set newVal to the value of the string "default". This can be used inline as well such as:
string newVal = "My data value contained a value of " + (myVal ?? "null") + ".";
Now you don't have to do any explicit if/then conditionals to check for nulls before assigning a value which is a great short cut. Remember though to be consistent - if your development team has a standards guide (which I'd recommend they do) then decide if this will become your teams preferred way of dealing with null checks. It gets to be cluttered code if you have half a team of developers using the coalescing operator and another half still writing out if/then condition checks.
Share this post: Email it! | bookmark it! | digg it! | reddit!