VB Quark #1: constant expressions

Posted Sat, Sep 24 2011 14:56 by bill

This quark is more of a did ya know quark about constant expressions in VB. You probably know you can declare a constant expression such :

   Const appName As String = "My Really Cool App"

But did you know you can also do operations in constants ?

Rather than calculate the area of a circle you can write:

   Const radius = 4.2
  
Const area = Math.PI * radius ^ 2

The compiler will calculate the area constant at compile time. This makes it easy to change the area constant by simply changing the radius.

The operations you can do include all the standard mathematical operations : +, –, /, \, * , ^ and Mod as well as bitwise operations such as And and Or as well as bit shifting << and >>.

For example you can declare an enum for bits using shift operations: (note: Enums are constants)

   Public Enum bits
      bit0 = 1
      bit1 = 1 << 1
      bit2 = 1 << 2
      bit3 = bit2 << 1
  
End 
Enum

 

You can also use the If operator. For example you might want to limit a constant based on another constant, eg if gravity is greater than 20g’s then you might want to limit it to 20g for calculations.

   Const workingG = If(g < 20 * 9.8, g, 20 * 9.8)

And you can also do conversions between the intrinsic numeric types, eg CDbl, CSng, CDec, CLng, CInt, CShort, CByte, CULng,  CUInt, CUShort, CSByte. And conversions to and from boolean to the numeric types: CBool and the aforementioned conversion operators.

   Const roughArea As Int32 = CInt(area)

For dates, there aren’t any operations or conversions you can do: you have to define them using the literal representation in US format, eg today 24/9/2011 is defined as #9/24/2011# . This is still a lot better than certain other languages (not picking on C#) that don’t support constant date literals.

For strings, you can’t do any conversions but can use the concatenation operator &. You can use + instead of &, but I don’t recommend that (more on that in another quark). Strings that are compiled as constants are also typically interned.

Anywhere you use an expression that can be compiled as a constant, it is evaluated at compile time: you don’t have to declare a constant variable to reap the benefits of compile time evaluation.

Comments

# VB Quark #2

Friday, September 23, 2011 11:31 PM by @ Head

Building upon VB Quark #1 , did you know you can use compiler directives alongside expressions in constants