|
The "And" operator is faster than "Mod"
|
Total Hit (4145) |
Using the "And" operator instead of "Mod" may speed up your program under certain situations. Use the And operator instead of Mod when the divisor is a number in the form 2^N. For instance, there are two methods to extract the least significant byte in an Integer:
«Code LangId=1»
lowByte% = valu
....Read More |
Rating
|
|
|
Avoid Integer Overflow
|
Total Hit (2956) |
When working with integer expressions there is often the risk of raising the "Overflow" error. More specifically, there can be two occasions when this frequently occurs:
When you multiply or add Integer values and the result exceeds 32,767.
When you create generic string routines that iterate
....Read More |
Rating
|
|
|
Convert Hexadecimal numbers
|
Total Hit (4170) |
While Visual Basic offers the Hex$ function that converts a decimal value into its hexadecimal equivalent number, it seems that the inverse function is missing. Not true. Try out this one-liner:
«Code LangId=1»
Function HexToDec(HexValue As String) As Long
HexToDec = Val("&H" & HexValue)
....Read More |
Rating
|
|
|
Counting Bits
|
Total Hit (3299) |
It seems that the only way to count the number of 1's or 0's in a binary value is creating a loop that iterates on all the 16 or 32 bits of the number. There is, however, a faster algorithm:
«Code LangId=1»
Function BitCount (ByVal number As Long) As Integer
Dim bits As Integer, temp As Long
....Read More |
Rating
|
|
|
Determine whether the app is running on a flawed Pentium CPU
|
Total Hit (2737) |
Here's a simple test that you can use to determine whether the application is running on a system equipped with a Pentium CPU affected by the FDIV bug:
«Code LangId=1»
' return True if the CPU suffers from the FDIV bug
Function IsBuggedPentium() As Boolean
IsBuggedPentium = ((1 / 3221224
....Read More |
Rating
|
|
|
Evaluate the integer equal or higher than a given value
|
Total Hit (2838) |
The VBA language offers the Int() function, which returns the integer equal or lower than a given value, but lacks a similar function that returns the integer equal or higher than a given value. You can remedy with the following function:
«Code LangId=1»
' Returns the integer equal or higher tha
....Read More |
Rating
|
|
|
|
Use the right type for constants
|
Total Hit (3116) |
VB stores symbolic and literal constants internally using the simplest data type possible; this means that most common numeric constants-such as zero or one-are stored as Integers. If you use these constants in floating point expressions you can speed up your code using a constant of appropriate typ
....Read More |
Rating
|
|
|
Write concise code with Boolean expressions
|
Total Hit (3102) |
When setting a Boolean value based upon the result of an expression, avoid using an unnecessary If/Then/Else structure.
«Code LangId=1»
'Instead of using this lengthy syntax . . .
If SomeVar > SomeOtherVar Then
BoolVal = True
Else
BoolVal = False
End If
'Use this one, which is easi
....Read More |
Rating
|
|
|
Write concise code with the Choose function
|
Total Hit (2935) |
The Choose function lets you often make more concise, albeit not faster, code, because it lets you replace a lengthy Select Case block. For example, the following code:
«Code LangId=1»
Select Case index
Case 1
result = 100
Case 2
result = 250
Case 3
resu
....Read More |
Rating
|
|
|
Write concise code with the IIf function
|
Total Hit (2191) |
Use IIf when setting a value based upon an expression. This works only in situations where you have two choices, based upon the result of a Boolean expression.
«Code LangId=1»
'long way
If Var1 > Var2 Then
Var3 = Var1 / Var2
Else
Var3 = Var2 / Var1
End If
'this is more concise
Var
....Read More |
Rating
|
|
|
Write concise code with the InStr function
|
Total Hit (2089) |
You can often use the Instr function in an unorthodox way to write more concise code. A typical example is when you need to test a single character:
«Code LangId=1»
' test whether CHAR contains a vowel
' the standard way
If UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCas
....Read More |
Rating
|
|
|
Write concise code with the Switch function
|
Total Hit (1773) |
Many VB developers don't realize that the Switch built-in function can often save a lot of code. This function takes any number of (expr, value) pairs, it evaluates all expressions and return the value related to the first expression that is found to be True. Typically you can use a Switch function
....Read More |
Rating
|
|
|
Write concise code: a collection of simple tips
|
Total Hit (2173) |
If you fully understand how VB and VBA work, you can often save some statements. This makes your listings more concise and more readable, and indirectly optimizes your program. Here is a short list of the many tricks you can use with this goal. You don't need to initialize a numeric variable to 0 or
....Read More |
Rating
|
|
|
A generic benchmark routine
|
Total Hit (3471) |
You often need to benchmark a piece of code, which you usually do as follows:
«Code LangId=2»
Dim start As Date = Now
' insert here the code to benchmark
Dim elapsed As TimeSpan = Now.Subtract(start)
Console.WriteLine("Total time: {0} secs.", elapsed)
«/Code»
Thanks to delegates, you can w
....Read More |
Rating
|
|
|
Add exception tracing with one line of code
|
Total Hit (3949) |
At times you want to keep a log of all the exception occurred in your application, including those that are correctly caught by a Catch block. At first you might believe that you need to add a call to the LogException procedure from each and every Catch block, which is clearly a nuisance:
«Code L
....Read More |
Rating
|
|
|
Create a unique GUID
|
Total Hit (4260) |
The System.Guid type exposes several shared and instance methods that can help you work with GUIDs, that is, those 128-bit numbers that serve to uniquely identify elements and that are ubiquitous in Windows programming. The most important member is the NewGuid shared method is useful for generating
....Read More |
Rating
|
|
|
Create console apps that return an exit code
|
Total Hit (3337) |
Writing an application that returns an ERRORLEVEL to Dos is quite difficult in VB6, because you are forced to use a Windows API that ends the application immediately, thus preventing orderly release of resources. Conversely, this task is quite simple in VB.NET, thanks to the Exit static method of th
....Read More |
Rating
|
|
|
Determine the size of a structure
|
Total Hit (4939) |
Unlike previous Visual Basic versions, under VB.NET you can't use the Len function to calculate the length of a Structure or a class. However, it is easy to get this information with the SizeOf static method of the System.Runtime.InteropServices.Mashal class, as in:
....Read More |
Rating
|
|
|
Evaluate an expression using the Microsoft Script Control
|
Total Hit (3695) |
Thanks to COM Interop, you can still use the Microsoft Script Control from VB.NET and any other .NET language. To do so, you must add a reference to the Microsoft Script Control library (from the COM page in the Add Reference dialog box): this action creates a new reference named Interop.MSScriptCon
....Read More |
Rating
|
|
|
Exclude code portions with the Conditional attribute
|
Total Hit (3345) |
VB developers have always used the #IF compiler directive to include or esclude portions of code from the application. The problem with this directive is that you can easily exclude a procedure with a single directive, but it isn't easy to discard all the calls to that procedure (which would raise a
....Read More |
Rating
|
|
|
Leverage the improved Shell function
|
Total Hit (3083) |
The version of the Shell function included in VB.NET expands on the original version and supports an additional argument that enables you to specify whether to wait until the shelled program terminates, with an optional timeout. This solves an old problem known to many Visual Basic developers withou
....Read More |
Rating
|
|
|
Providing a default value for optional arguments
|
Total Hit (3359) |
Unlike VB6, VB.NET requires that you specify the default value of any Optional argument. In general you should use a value that is invalid under normal circumstances, so that the called procedure can discern whether the argument has been actually passed or not. For example, you should use -1 as a sp
....Read More |
Rating
|
|
|
Retrieving the hi/low byte/word of a value, and other operations
|
Total Hit (4405) |
As explained in the tip about the ARGBColor structure (look at the end of this tip for the link), we can define a structure and have its fields that point to the same memory address, but that read a different number of bytes. This makes easier to define a structure that allows us to set a value to a
....Read More |
Rating
|
|
|
Use a ParamArray as a true array
|
Total Hit (2782) |
Unlike VB6, in VB.NET the ParamArray keyword defines a true array object, which you can process using any of the methods of the Array class. For example, here' s a function that evaluates the lowest value among those passed to the procedure, using the static Array.Sort method and then taking the ele
....Read More |
Rating
|
|
|
Use the Err.GetException method to create custom exceptions
|
Total Hit (3021) |
The Visual Basic .NET Err.Raise method and the Throw command are (partially) compatible. For example, you can use a Try...End Try block to catch an error raised with the Err.Raise method, and you can use an On Error Resume Next and the Err object to neutralize and inspect an exception object created
....Read More |
Rating
|
|
|
Using a union to retrieve the RGB components of a color
|
Total Hit (3035) |
In VB.NET you can create what in C is called a union, i.e. a particular structure where you can access the same memory with different names. Here's how you declare such a structure by using the StructLayout attribute, and specifying that you want to define the structure layout explicitly, namely how
....Read More |
Rating
|
|
|
Using aliases to quickly change the type of variables
|
Total Hit (3231) |
It may happen that you have to define a lot of variable of some type, and you want the possibility to later change their type without manually change the declaration of all of them. You can't use a simple Find & Replace, because you don't want to change the type of ALL the variables of that original
....Read More |
Rating
|
|
|
Write applications that take arguments
|
Total Hit (3949) |
C# has a nice feature that VB.NET lacks: the ability to define a Main procedure that takes an array of strings, each one containig one of the arguments passed on the command line. It's easy to mimick this feature in VB, though.
In fact, while the Command function is still supported in VB.NET, you
....Read More |
Rating
|
|
|
A simple expression evaluator
|
Total Hit (3412) |
While any Windows user could pop up the Calculator accessory to perform any type of math calculations, it would be great if you could offer him or her the capability to do simple math from within your application. This is a very simple expression evaluator function that does it:
This evaluator i
....Read More |
Rating
|
|