Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean properties in c#

Tags:

c#

.net

boolean

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; }
like image 835
slandau Avatar asked Nov 10 '11 21:11

slandau


People also ask

What is a bool property?

The bool type keyword is an alias for the . NET System. Boolean structure type that represents a Boolean value, which can be either true or false .

How do you set a Boolean value in Objective C?

To set a BOOL, you need to wrap the number in a value object with [NSNumber numberWithBool:NO] . But there's little reason to do that. Key-Value Coding is a roundabout way to accomplish this. Either do self.

What is Boolean in Objective C?

Boolean, in Objective-C, is a hold over data type from the C language. Both in C, and hence in Objective-C, 0 (zero) is treated as “false” and 1 (one) as “true”. C has a Boolean data type, bool (note: the lowercase), which can take on the values of true and false.


3 Answers

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.

like image 178
Eric Lippert Avatar answered Sep 19 '22 08:09

Eric Lippert


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

like image 45
BrokenGlass Avatar answered Sep 19 '22 08:09

BrokenGlass


no, Boolean defaults to false. So

bool something; // something is false
like image 32
Joe Avatar answered Sep 18 '22 08:09

Joe