I have a sample piece of code with me:
bool _HasParsed;
object IsCheckedAsObj = GetCheckedStatus();
if (IsCheckedAsObj == null)
{
throw new InvalidOperationException("Status not found");
}
_HasParsed = (bool?)IsCheckedAsObj; //why (bool?) instead of (bool)
In the last line, I can understand that they are parsing the object to boolean. But what is that ‘?’ doing there? Whats the difference between (bool?) instead of (bool)?
The type
bool?is shorthand forNullable<bool>.The code doesn’t compile as it stands. You will get the error message “Cannot implicitly convert type ‘bool?’ to ‘bool’.”.
If you declare the variable as nullable too, it will work:
That might of course mean that you need to do other changes in the code. You can use
_HasParsed.HasValueto check if the variable is not null, and use_HasParsed.Valueto get the bool value.