160 likes | 351 Views
Arrays, Types, and Conversions. Motivation. We already know the concept of arrays and records in Pseudocode. Let's extend that to VB Also, we know that VB will automatically do type conversions for us, but that can be dangerous, so lets learn more…. Arrays in VB. Fixed size
E N D
Motivation We already know the concept of arrays and records in Pseudocode. Let's extend that to VB Also, we know that VB will automatically do type conversions for us, but that can be dangerous, so lets learn more…
Arrays in VB • Fixed size dim ARRAY_IDENTIFIER(UBOUND) as TYPE ' implicit 0 LBOUND dim ARRAY_IDENTIFIER(LBOUND to UBOUND) as TYPE • Example dim arrGrades(1 to 30) as Single
Arrays in VB • Variable size dim ARRAY_IDENTIFIER() as TYPE ReDim ARRAY_IDENTIFIER(NEW_UBOUND) ReDim ARRAY_IDENTIFIER(NEW_LBOUND to NEW_UBOUND) • Example dim arrGrades() as Single ReDim arrGrades(1 to 30)
Multidimensional Arrays in VB • Separate the bounds with commas dim ARRAY_IDENTIFIER(UBOUND1, UBOUND2, …) as TYPE
Option Base • Notice that all arrays default their LBOUND to 0 • We can make the default anything we'd like Option Base NEW_DEFAULT
Preserving Contents when ReDim'ing • What if you have a variable-size array that's already got data in it • You'd like to increase the size to make room for more data • But you don't want to lose the current data • Use PRESERVE ReDim Preserve arrGrades(30)
Types (Records) in VB • You can define your own user-defined types in VB (similar to records in Pseudo-code) • General modules: public or private types • Form modules: only private types Public/Private Type TYPE_NAME FIELDS End Type
Type Example Private Type StudentType Name as String Age as Integer GPA as Single Is_Female as Boolean End Type
Accessing Fields • Use the dot (".") operator Student1 as StudentType Student1.Name = "Jon" Student1.Age = 28 Student1.GPA = 3.56 Student1.Is_Female = FALSE
Converting Data of Different Types • We know VB does this automatically as best as it can • The catch is "as best as it can" • What happens when I do the following? "100" + "10"
10010? • "100" + "10" is string concatenation, so you get "10010" - not 110 (what we might want if a user entered two numbers into text boxes) • Let's discuss ways of forcing VB to convert types as we want (non-automatically)
Type Conversion Functions Boolean CBool() Byte CByte() Currency CCur() Date CDate() Double CDbl() Integer CInt() Long CLng() Single CSng() String CStr() Variant CVar()
Is (Type checking) • You can also determine if a variable is of a particular type • IsNumeric(VAR) • IsDate(VAR) • IsArray(VAR) • IsObject(VAR) • More generally: VarType(VAR)
Summary • VB arrays can be fixed or dynamic • VB arrays can be multidimensional • You can create your own types in VB • It's important to understand types and conversion routines