Reputation: 24052
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
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
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
Reputation: 32936
public bool? PrepaymentCalculating { get; set; }
will make it nullable. Read about it here
Upvotes: 5
Reputation: 17018
If you want it to be null then you need to make it a nullable type.
Upvotes: 1
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
Reputation: 108937
try
public bool? PrepaymentCalculating { get; set; }
Here's a post on Nullable Types
Upvotes: 5