//always works, returning a valid object into _page
_page = _httpContext.Handler as System.Web.UI.Page;
//Fails throwing the exception : Unable to cast object of type 'System.Web.DefaultHttpHandler' to type 'System.Web.UI.Page'
_page = (System.Web.UI.Page)_httpContext.Handler;
I would like to know why this happens?
EDIT:
//Fixes the problem
if(_httpContext.Handler is System.Web.UI.Page)
_page = (System.Web.UI.Page)_httpContext.Handler;
If i debug the ‘as’ keyword statement, i never get a null reference (object always assigned properly). However the () cast creates exceptions unless it has the if statment.
EDIT: After about 15 runs through the class i was able to get a null. Seems like it took more runs to find a null compared to how fast the () cast would catch an exception.
OLD: When there is a debug at the ‘as’ statement every time the class runs the break point hits – never null.
When tthere is a debug in the ‘()’ statement within the if, every time the break point hits the cast works properly. Werid
This didn’t technically work. If you’ll notice
_pagewill benull. It just didn’t throw an error.The
asoperator is used to tell the application “I want you to try and convert this. It might not, and I know this, so don’t throw an exception. I’ll deal with it accordingly.”The
()conversion is used to tell the application, “This object will cast to this type. If it doesn’t something is wrong, and I need to know about it.”The difference between the two casts (and when you should use them) is when you “think” something is castable to another type and when you “know” something is castable to another type.
Here is an article by Eric Lippert on the subject (changed to his blog not re-feeded):
http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx