How to convert bool? to bool in C#?

How do you convert a nullable bool? to bool in C#?

I have tried x.Value or x.HasValue ...


You ultimately have to decide what the null bool will represent. If null should be false, you can do this:

bool newBool = (x.HasValue) ? x.Value : false;

Another way:

bool newBool = x.HasValue && x.Value;

You can use the null-coalescing operator: x ?? something, where something is a boolean value that you want to use if x is null.


bool? myBool = null;
bool newBool = myBool ?? false;

newBool will be false.

You can use Nullable{T} GetValueOrDefault() method. This will return false if null.

 bool? nullableBool = null;

 bool actualBool = nullableBool.GetValueOrDefault();

Need Your Help

Creating a Serial Port in code in visual-studio serial-port

I am trying to create a serial port in using code only. Because I am creating a class library I cannot use the built-in component. I have tried instantiating a new SeialPort() object, but that

Html Agility Pack, Web Scraping, and spoofing in C#

c# web-scraping html-agility-pack spoofing

Is there a way to spoof a web request from C# code so it doesn't look like a bot or spam hitting the site? I am trying to web scrape my website, but keep getting blocked after a certain amount of ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.