Avoiding That Null Reference!

Posted by TheJuice on Geeks with Blogs See other posts from Geeks with Blogs or by TheJuice
Published on Wed, 23 Feb 2011 18:27:45 GMT Indexed on 2011/02/23 23:26 UTC
Read the original article Hit count: 333

Filed under:

A coworker had this conversation with another of our developers. Names have been changed to protect the guilty.

Clueless: hey!
Clueless: I am using the ?? operator for null check below

Nice Guy: hey

Clueless:
FundLoanRequestBoatCollateral boatCollateral = request.BoatCollateral ?? null;


Nice Guy:
that's not exactly how it works

Clueless: I want to achive:
FundLoanRequestBoatCollateral boatCollateral = request.BoatCollateral != null ? request.BoatCollateral : null;
Clueless: isnt that equal to: 
FundLoanRequestBoatCollateral boatCollateral = request.BoatCollateral ?? null;

Nice Guy: that is functionally equivalent to
FundLoanRequestBoatCollateral boatCollateral = request.BoatCollateral

Nice Guy: you're checking if it's null and if so setting it to null

Clueless: yeah
Clueless: if its null I want to set it to null

Nice Guy: if it's null then you're already going to set it to null, no special logic needed
Clueless: I wanted to avoid a null reference if BoatCollateral is null

 

The sad part of all of this is that "Clueless" has been with our company for years and has a Master's in Computer Science.

© Geeks with Blogs or respective owner