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!
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.
As Nico's answer hints at, you can use the as
operator if you cast to a Nullable<T>
That means you can do this:
TempData["sortBool"] as bool?
If you want it to default to a bool value instead of a nullable, you can also use null-coalescing to get the default like this:
TempData["sortBool"] as bool? ?? false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With