Friday, January 12, 2007

The "as" operator as described in MSDN is an operator: "Used to perform conversions between compatible reference types". We have to keep this in mind when coding. Often it is just easier (and it looks nicer too) to use an "as" operator instead of a cast, or when we want to handle the DBNull value returned from the database like in the following scenario:

string s = reader["Name"] as string;

instead of

string s = (string)((reader["Name"] is DBnull) ? null : reader["Name"]);

Assuming that the name column can be null in the database.

When we use it we accept that something could be of incompatible type such as Name column being of numeric type return. What happens then? What happens if the column type has changed? In the scenario above, we will always get a null reference, which in a worst case scenario we will discover very late in project.

Of course in some situations it is just what we need. What I have found however is that misusing the "as" operator can often lead to unexpected NullReferrenceException exceptions being thrown (or worse yet nothing wrong happens at first). If you find that happening it may mean that you are using "as" operator as a shortcut where an ordinary cast would be in place. Using a cast often causes bugs to appear sooner in the development life cycle which is always a nice thing. So basically a rule of thumb is to always think twice whether to use a cast or an "as" operator.

kick it on DotNetKicks.com

Saturday, January 13, 2007 8:53:22 AM (Central European Standard Time, UTC+01:00)
As a practice, for avoiding null reference exception, the code can be modified from

string s = reader["Name"] as string;

to

string s = reader["Name"] as string ?? string.empty;

What the '??' will do is that if the preceeding value is evaluated to null, it will be replaced by the following value (i.e. string.empty in case above). This provides you a 'neat' option to specify a default value in case a null is expected.

You can, however, use this in .Net 2.0 or later only.
Rajdeep Kwatra
Monday, January 15, 2007 10:29:51 AM (Central European Standard Time, UTC+01:00)
Unfortunately modifying the code in a way you suggest changes the real value of "Name" from no value to an empty value. Which I don't want to happen.
Monday, January 15, 2007 10:37:54 AM (Central European Standard Time, UTC+01:00)
The code mentioned addresses, in particular, the prevention of NullReferenceException while accessing the value of 's'. The actual usage/implementation depends upon the requirements at hand.
Rajdeep Kwatra
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview