slandau
slandau

Reputation: 24052

Default value for bool in c#

public bool PrepaymentCalculating { get; set; }

So I declare a variable on one of my classes like that. I want this to default to 'null' and not false. Would I just need to make this a nullable boolean? Or is there a better way to do this?

Upvotes: 7

Views: 11774

Answers (6)

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

Like everyone else said, but I thought I'd add, what's your purpose here? It's not often that I want to expose a nullable bool, since this means that everything that uses this property must account for a possible null value.

But sometimes I want to know if it's been initialized or not in a given context, and if not, then use a value from somewhere else (e.g. to cascade property values). In this case you might want to use a pattern like this:

public bool PrepaymentCalculating { 
    get {
        if (_PrepaymentCalculating != null ) {
            return (bool)_PrepaymentCalculating;
        } else {
            return somethingElse; // bool
        }
    }
    set {
      _PrepaymentCalculating = value;
    }
} protected bool? _PrepaymentCalculating =null;

Upvotes: 1

jason
jason

Reputation: 241601

Would I just need to make this a nullable boolean?

Yes.

Or is there a better way to do this?

No.

You can achieve this with

public bool? PrepaymentCalculating { get; set; }

Upvotes: 16

Sam Holder
Sam Holder

Reputation: 32936

public bool? PrepaymentCalculating { get; set; }

will make it nullable. Read about it here

Upvotes: 5

Stefan Egli
Stefan Egli

Reputation: 17018

If you want it to be null then you need to make it a nullable type.

Upvotes: 1

Tridus
Tridus

Reputation: 5081

bool can't be null. The default is probably false (but don't quote me on that).

If you want it to be null, then yes you have to declare it as nullable.

Upvotes: -1

Bala R
Bala R

Reputation: 108937

try

public bool? PrepaymentCalculating { get; set; }

Here's a post on Nullable Types

Upvotes: 5

Related Questions