CInt() is a command used to try and convert whichever argument, i.e. the item placed between the two parenthesis, into an integer.
This is very useful for creating safer programs. Consider the code snippet below:
What happens if someone inputs "butts lol" into the textbox?
Typically, the program would crash. Now let's look at the safe version of this same code:
What happens to this code if someone inputs "LMFAO poooop" into the textbox?
Well, nothing exciting. The value 0 would be assigned to myInt.
There are other built-in safe conversions as well, such as CDbl() for doubles, CDec for decimals, etc.
For a full list, see the MSDN (MicroSoft Developer Network) reference at:
Type Conversion Functions (Visual Basic)
Inline declaration allows users to both declare multiple variables all in the same line, and assign them a value at creation.
This can turn the following code:
Into a single line, such as:
Like (almost) all things in code, this is a trade. The declaration is more compact, but may be less legible for new coders.
Since either is correct, use whichever makes more sense to you. That said, it is far more common to see code more similar to the second snippet in industry.
A single-line if statement allows for compact, simple branching.
This allows us to really crunch down on any if/then/else statement that is only running one line of code per condition.
For example:
Can be smashed down to:
Which does the exact same thing.
Functions and Subroutines (Subs) are used to make code more modular. This seems like more buzzword than something useful,
but hopefully the following examples can demonstrate their usefulness.
The big difference between Functions and Subs is that a Function MUST RETURN A VALUE. What does this mean?
Let's look at the snippet below and see if we can make sense of them.
The calls at the bottom do the same thing. So what is the benefit of using a Function as opposed to a Sub?
The idea is really modularity. What if I want to add two values without popping a message box? The addDos() function doesn't help there.
Because the addTwo function allows us to chain, we can also add use the two in unison. What if we want to add 1 through 4? Well, we can just do this:
addDos(addTwo(1,2),addTwo(3,4))
Of course, these example are trivial... since we can just use the "+" operation. But hopefully they illustrate the idea of when to use a function as opposed to a sub.
Modularity and Code Reuse
How does this tie into modularity and code reuse? Think of the following example, related to lab 11. We could do the starsBtn_click like this:
But instead, for legibility (and modularity!) it is done like this:
Even ignoring the differences in return/if structure, the second block of code is far more useful if we were to ever use this code for anything else.