Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 16th, 2012  |  syntax: None  |  size: 1.12 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to convert bool? to bool in C#?
  2. bool newBool = (x.HasValue) ? x.Value : false;
  3.        
  4. bool? nullableBool = null;
  5.  
  6.  bool actualBool = nullableBool.GetValueOrDefault();
  7.        
  8. if (bn.HasValue)
  9.         {
  10.             b = bn.Value
  11.         }
  12.        
  13. bool b1;
  14. bool? b2 = ???;
  15. if (b2.HasValue)
  16.    b1 = b2.Value;
  17.        
  18. bool b3 = (b2 == true); // b2 is true, not false or null
  19.        
  20. bool? x = ...;
  21. if (x ?? true) {
  22.  
  23. }
  24.        
  25. bool converted = (bool)x;
  26.        
  27. bool? b = ...;
  28.  
  29. if (b == true) { Debug.WriteLine("true"; }
  30. if (b == false) { Debug.WriteLine("false"; }
  31. if (b != true) { Debug.WriteLine("false or null"; }
  32. if (b != false) { Debug.WriteLine("true or null"; }
  33.        
  34. bool? b = ...;
  35.  
  36. if (b == null) { Debug.WriteLine("null"; }
  37. if (b != null) { Debug.WriteLine("true or false"; }
  38. if (b.HasValue) { Debug.WriteLine("true or false"; }
  39. //HasValue and != null will ALWAYS return the same value, so use whatever you like.
  40.        
  41. bool? b = ...;
  42. bool b2 = b ?? true; // null becomes true
  43. b2 = b ?? false; // null becomes false
  44.        
  45. bool? b = ...;
  46. if(b == null)
  47.     throw new ArgumentNullException();
  48. else
  49.     SomeFunc(b.Value);
  50.        
  51. bool? a = null;
  52. bool b = Convert.toBoolean(a);