开发者

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? O开发者_开发技巧r 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


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


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜