The 'as' operator in C#

Date Added: June 01, 2010 08:51 by By Edward
Categories: ASP.NET, Other

The 'as' operator is a "type", and is just like the cast operator except that it will return NULL on a conversion failure instead of throwing an exception. The 'as' operator is used to perform conversions between compatible types and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.

For example:

 

Object objValue = new Object();              
string strA = (string)objValue; //Cast throws an Exception              
string strB = objValue as string; //No exception is thrown, but strB is set to NULL

 

The 'as' operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net