I am extracting a bool value from a (non-generic, heterogeneous) collection.
The as operator may only be used with reference types, so it is not possible to do use as to try a safe-cast to bool:
// This does not work: "The as operator must be used with a reference type ('bool' is a value type)"
object rawValue = map.GetValue(key);
bool value = rawValue as bool;
Is there something similar that can be done to safely cast an object to a value type without possibility of an InvalidCastException if, for whatever reason, the value is not a boolean?
There are two options… with slightly surprising performance:
Redundant checking:
Using a nullable type:
The surprising part is that the performance of the second form is much worse than the first.
In C# 7, you can use pattern matching for this:
Note that you still end up with
valuein scope (but not definitely assigned) after theifstatement.