Booleans - True or False?


Booleans – True or False?

A Boolean is a data type that can store one of two states – whether you choose to call it true/false, yes/no, on/off, 1/0, or whatever. Visual Basic .NET calls the two values True and False.

If you're new to programming, you might not think it's very useful to store something so simple in memory. After all, the chances of wanting to store one of just two fixed possibilities is pretty remote, right? Wrong. Booleans are used whenever you use a computer to make a decision. For example when you compare two values to see if they are equal, you state "value1 = value2" and are told that the statement is either True or False. Also, it takes up less memory space for a simple true/false evaluation.

This is how the If statement works. If expects you to give it a True or False value. Give an If statement a True condition and whatever follows the condition will run. Give the If statement a False condition, however, and whatever follows the Else will run:

 If myBooleanValue Then  ' This runs if myBooleanValue = True Else  ' This runs if myBooleanValue = False End If 

You have seen this kind of construct in code many times before, but now you should understand how the code knows what to do and where to go.

Declaring a variable as a Boolean is just like declaring any other variable:

 Dim myBooleanValue As Boolean 

Often, you will want to perform the steps from the If ... Then statement a while after you've decided whether you are going to perform them. Saving the Boolean lets you do this. It enables you to remember a decision, and then act on that decision later.

Booleans are also great at acting as little switches. Let's say you needed to know whether a vital operation has already taken place or not. All you would have to do is create a Boolean and set it to True to indicate that it has taken place, and False if it hasn't:

 AlreadyDoneThis = True 

You can also use Booleans as arguments, which is often a very useful way of providing 'optional extras' to your functions:

 Function validateCard(rejectCardIfWrong As Boolean) As Boolean 

That's all you really need to know about Booleans for now – simple aren't they?! They are very useful though, and before long you'll be using them all over the place.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net