Search code examples
asp.net-mvcasp.net-mvc-4tempdata

TempData["sth"] as bool


This is ok:

(bool)TempData["sortBool"]

This is not ok:

TempData["sortBool"] as bool

The error states that:

Error   1   The as operator must be used with a reference type or nullable type ('bool' is a non-nullable value type)   C:\Users\xye15\Desktop\CodeChallengeV4\CodeChallengeV4\MovieKiosk\Controllers\HomeController.cs 55  21  MovieKiosk

I understand why the second is wrong, plain as the error message. But I got confused why the compiler not complaining about the first one. Thanks!


Solution

  • A simple cast is fine. It will throw an exception if the cast does not work. The compiler cannot evaluate if the cast will work, so there will be no compile errors.

    The as operator does a bit more than casting. It returns null if the cast is not successful. Therefore, the return type has to support a null value, which is the case for reference types and Nullable<T>. as bool's return type is bool. This type does not support a null value and you end up with a compile error.