简体   繁体   中英

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?

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; }

try

public bool? PrepaymentCalculating { get; set; }

Here's a post on Nullable Types

public bool? PrepaymentCalculating { get; set; }

will make it nullable. Read about it here

如果您希望它为null,那么您需要使其成为可空类型。

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 (eg 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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM