Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 965
bookmonkie Avatar asked Feb 12 '23 11:02

bookmonkie


2 Answers

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.

like image 129
Nico Schertler Avatar answered Feb 19 '23 03:02

Nico Schertler


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

like image 27
HotN Avatar answered Feb 19 '23 04:02

HotN