Home > Mobile >  what does " if (! nullableBool.Value ) " mean?
what does " if (! nullableBool.Value ) " mean?

Time:01-03

I try to code the Nullable value concept in C#, but don't know what does "if (!i.value)" means or what return, Is it supposed to be "true" or what?

class CSharp
    {
        static void Main(string[] args)
        {
            bool? i = false;
            
            if(!i.Value)
            {
                Console.WriteLine("false");
            }
            else if(i==true)
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("null");
            }
        }
    }

CodePudding user response:

If .Value doesn't exist, this will throw an InvalidOperationException. If you want to check if the variable has a value, use the HasValue attribute instead.

You could do something like this:

class CSharp
{
    static void Main(string[] args)
    {
        bool? i = false;
        
        if(!i.HasValue)
        {
            Console.WriteLine("null");
        }
        else if(i.Value)
        {
            Console.WriteLine("true");
        }
        else
        {
            Console.WriteLine("false");
        }
    }
}

Documentation

CodePudding user response:

In C#:

if (!i.Value) {

In VB.Net

If Not i.Value Then

I'm not sure why they made it a Nullable bool? when they assign it false. You're better off writing it like this:

bool isAYesOrNoVariable = false;           
if(!isAYesOrNoVariable) {
  •  Tags:  
  • c#
  • Related