Search code examples
c#.netwinformslinqlinq-to-entities

how to convert the bool to nullable bool (bool?)


i have a table provider with column

                 implied(tiny int)(something like nullable bool)
                 providerid(int)

I have a form and i have check box

I am doing winforms applications using c# ..

i am using enitities and my dbcontext name is dbcontext

How to covert bool to nullable bool(bool?) in C sharp.

I have tried this way

      if (chkbox.checked == true)

            bool yes = 0;
        else

          bool   yes = 1;

        dbcontext.implied = yes;

but got an error

Cannot convert bool to bool?

Solution

  • Explicitly cast to a bool?

    bool b = true;
    bool? b2 = (bool?)b;
    

    In case it's of interest, you can convert bool? to bool. You can do this by first checking HasValue which will return false if it's null or true if it is not null.

    If it does have a value, you can cast to a bool.

    bool? b = null;
    if (b.HasValue == false) // it's null
    {
      //initialize b 
      b = false;
    }
    else if((bool)b == true)
    {
      // do whatever
    }
    

    Check out http://msdn.microsoft.com/en-us/library/bb384091.aspx for bool? to bool conversion.