Using the as keyword versus boxing in C#

When I convert one object to another using the keyword “as” and the original value is not of that type, the converted value simply becomes NULL. For example, if theItem is of type MessageBox, then row will be NULL.

DataRowView row = theItem as DataRowView;

However, when using this code, I.e. boxing.

DataRowView row = (DataRowView)theItem;

An InvalidCastExcpetion is thrown. I think I’ll start using “as” more in my code versus the boxing technique I have been using in the past. I like to avoid throwing exceptions even though I always place my code in a try…catch block.




Leave a Comment

Your email address will not be published.