Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast nullable bool to bool

Tags:

c#

I have an object AlternateName.IsMaidenName

I want to cast that to a checkbox - IsMaidenName

It wont let me cast that as it says Cannot convert source type nullable to target type bool.

I've had this issue in other spots within our application but I wanted to throw it out there for a better way to handle these issues.

IsMaidenNameChecked = AlternateName.IsMaidenName;
like image 638
gevjen Avatar asked Feb 17 '11 16:02

gevjen


2 Answers

It is quite logical that you cannot cast a nullable bool to a bool, since, what value should the bool have, when the nullable contains null ?

What I would do, is this:

IsMaidenNameChecked = AlternateName.IsMaidenName ?? false;
like image 178
Frederik Gheysels Avatar answered Oct 13 '22 00:10

Frederik Gheysels


IsMaidenName.Checked = AlternateName.IsMaidenName.GetValueOrDefault();

See: http://msdn.microsoft.com/en-us/library/72cec0e0.aspx

like image 34
Daniel A. White Avatar answered Oct 13 '22 00:10

Daniel A. White