Boolean properties in c#

31,065

Solution 1

This might be a dumb question

It is not.

in the property below, will there ever be a situation where just getting it will cause an exception?

Possibly, yes. For example, another thread could abort your thread while it was in the middle of fetching that property; that would appear to be an exception thrown by the property getter. Or, you could run out of stack space right at the moment where the property is called, and an out-of-stack exception could be thrown. Or, when you call the property for the first time, the jitter might start up and try to allocate virtual memory for the generated code, but you are all out of virtual address space, so an out of memory exception could be thrown.

Those are all extraordinarily unlikely, but they are all possible. You asked if there would ever be such a situation, not if it was likely.

If I hadn't set BatchValuation yet, will it just set value to null, or will it cause an exception?

Neither; it will default to false. Booleans are not nullable.

Solution 2

boolean values default to false if you have not set them specifically. So no there will be no exception, the property will just return false.

Remember that this is a value type we are talking about, only variables for reference types can be set to null. Value types do have a default value, which is zero for numeric types and false for boolean.

Also see Default Values Table

Solution 3

no, Boolean defaults to false. So

bool something; // something is false

Solution 4

In the context of class properties or member fields, each field is initialized to a default value for the type when the class is created prior to the constructor being run. In the class

class Foo
{
    bool bar;
    string s;
    int item;
    public double Baz { get; set; } 
}

The first three fields are set to their initial values (false, null, and 0, respectively), and the auto-generated backing field for Baz is also set to 0.0d. It is not an error to access these fields/properties without explicit user-initialization, unlike accessing uninitialized locals. It is for locals that the compiler requires explicit initialization.

class Foo
{
   int bar;

   void M()
   {
       Console.WriteLine(bar); // not an error, bar is 0;
       bool someBool;
       Console.WriteLine(someBool); // use of uninitialized local variable
   }
}
Share:
31,065
slandau
Author by

slandau

Updated on November 11, 2020

Comments

  • slandau
    slandau over 3 years

    This might be a dumb question, but the property below, will there ever be a situation where just getting it will cause an exception?

    Like if I did something like bool value = this.BatchValuation; - but I hadn't set BatchValuation yet, will it just set value to null, or will it cause an exception?

    public bool BatchValuation { get; set; }