Lesson 8 · Data Types

Understanding Data Types

Learn how Visual Basic 2026 classifies and stores data — numeric types, strings, booleans, dates, and objects — how to choose the right type for every situation, perform safe type conversions, and avoid common overflow errors, with GitHub Copilot assistance.

Key Takeaway: Every piece of data in VB 2026 has a data type that determines how much memory it uses, what values it can hold, and what operations are valid. Choosing the right type prevents bugs, saves memory, and improves performance. Integer for whole numbers, Double for most decimals, Decimal for money, String for text, Boolean for True/False, and Date for date/time values. In .NET 10, VB 2026 also introduces improved type inference — the compiler can often deduce the type automatically from the assigned value.

8.1 The Two Main Categories

VB 2026 divides all data types into two broad categories:

🔢 Numeric — Integer (Whole Numbers)
Byte0 to 255 · 1 byte
Short−32,768 to 32,767 · 2 bytes
Integer−2.1 B to 2.1 B · 4 bytes ⭐ most common
Long−9.2 × 10¹⁸ to 9.2 × 10¹⁸ · 8 bytes
UInteger0 to 4.3 B · 4 bytes (unsigned)
ULong0 to 1.8 × 10¹⁹ · 8 bytes (unsigned)
📐 Numeric — Floating Point (Decimals)
Single±3.4 × 10³⁸ · 4 bytes · ~7 sig digits
Double±1.8 × 10³⁰⁸ · 8 bytes · ~15 sig digits ⭐
Decimal28–29 significant digits · 16 bytes · exact ⭐ money
📝 Text
StringAny text · 0 to ~2 billion chars · Unicode
CharSingle character · 2 bytes · Unicode
✅ Boolean
BooleanTrue or False · 2 bytes
📅 Date & Time
DateJan 1 0001 – Dec 31 9999 · 8 bytes
🔷 Other
ObjectAny value — late bound · 4/8 bytes ptr
StructureCustom value type · user-defined

8.2 Numeric Data Types in Detail

Integer — the Workhorse

Integer is the most commonly used numeric type. It stores whole numbers from −2,147,483,648 to 2,147,483,647 and operations on it are the fastest of any numeric type on 32-bit and 64-bit CPUs.

NumericTypes.vb — Visual Basic 2026
' Integer — whole numbers, most common choice
Dim age       As Integer = 25
Dim score     As Integer = -150
Dim maxItems  As Integer = 2_147_483_647   ' digit separator for readability (.NET 10)

' Long — when Integer isn't big enough
Dim population As Long = 7_900_000_000L  ' world population — exceeds Integer limit
Dim fileBytes  As Long = 1_073_741_824L  ' 1 GB in bytes

' Double — decimal numbers, ~15 significant digits
Dim height     As Double = 1.75
Dim pi         As Double = 3.14159265358979
Dim gravity    As Double = 9.80665

' Decimal — EXACT precision for money calculations
Dim price      As Decimal = 19.99D          ' D suffix = Decimal literal
Dim taxRate    As Decimal = 0.06D
Dim total      As Decimal = price * (1D + taxRate)

' Type inference — compiler deduces type from value (.NET 10)
Dim quantity  = 42           ' inferred as Integer
Dim rate      = 3.14         ' inferred as Double
Dim name      = "Alice"      ' inferred as String
⚠ Double vs Decimal — Critical Difference

Double uses binary floating-point and can produce tiny rounding errors: 0.1 + 0.2 in Double gives 0.30000000000000004. For financial calculations (prices, tax, interest) always use Decimal — it stores values in base-10 and avoids these errors. Double is fine for scientific measurements where small rounding doesn't matter.

Try It — Simulation 8.1: Numeric Type Explorer

Enter a number and select a data type. See whether the value fits, its memory size, and the VB 2026 declaration syntax.

Numeric Type Explorer
Enter a value:
Data Type:
Result:

8.3 String, Char, and Boolean

String

The String type stores Unicode text of any length. Strings in VB 2026 are immutable — when you "change" a string you are actually creating a new one in memory. Use StringBuilder for intensive string-building operations in loops.

StringTypes.vb — Visual Basic 2026
' String declaration
Dim firstName  As String = "Alice"
Dim lastName   As String = "Wong"
Dim empty      As String = ""               ' empty string
Dim nothing    As String = Nothing          ' null reference

' String interpolation (preferred in VB 2026)
Dim greeting  As String = $"Hello, {firstName} {lastName}!"

' String functions
Dim upper     = firstName.ToUpper()           ' "ALICE"
Dim length    = firstName.Length               ' 5
Dim trimmed   = "  hello  ".Trim()           ' "hello"
Dim contains  = firstName.Contains("lic")    ' True

' Char — single character
Dim initial  As Char = "A"c                 ' c suffix = Char literal
Dim firstChar = firstName(0)                  ' "A" — index access

' Test for empty/null safely
If String.IsNullOrWhiteSpace(firstName) Then
    lblStatus.Text = "Name is required."
End If

Boolean

The Boolean type holds only True or False. It is the result type of all comparison and logical operators, and the standard type for flag variables and condition checking.

BooleanTypes.vb — Visual Basic 2026
Dim isLoggedIn   As Boolean = False
Dim hasPermission As Boolean = True
Dim isAdult       As Boolean = (age >= 18)    ' result of comparison

' Logical operators
Dim canAccess = isLoggedIn AndAlso hasPermission  ' short-circuit And
Dim needsHelp = Not isLoggedIn OrElse Not hasPermission

' Toggle a flag
isLoggedIn = Not isLoggedIn

' Use in If statement
If canAccess Then
    lblWelcome.Text = "Welcome!"
Else
    lblWelcome.Text = "Access denied."
End If
💡 AndAlso vs And — Always Prefer AndAlso

AndAlso is a short-circuit operator — if the left side is False, it does not evaluate the right side. This prevents errors like calling a method on Nothing. And evaluates both sides always. In VB 2026, prefer AndAlso and OrElse in almost all cases.


8.4 Date and Time

The Date type stores both a date and a time component. It maps directly to .NET's DateTime structure and supports a rich set of methods for date arithmetic, formatting, and parsing.

DateTypes.vb — Visual Basic 2026
' Date literals — use # delimiters
Dim independence As Date = #8/31/1957#         ' Malaysia Independence Day
Dim newYear      As Date = #1/1/2026 12:00:00 AM#

' Current date/time
Dim now     As Date = DateTime.Now             ' local date + time
Dim today   As Date = DateTime.Today           ' date only, time = 00:00

' Accessing parts
Dim yr   = now.Year       ' e.g. 2026
Dim mo   = now.Month      ' 1–12
Dim dy   = now.Day        ' 1–31
Dim hr   = now.Hour       ' 0–23

' Date arithmetic
Dim deadline     = today.AddDays(30)           ' 30 days from now
Dim nextMonth    = today.AddMonths(1)
Dim daysSince    = (today - independence).TotalDays

' Formatting
Dim formatted    = now.ToString("dd/MM/yyyy")  ' "22/02/2026"
Dim withTime     = now.ToString("dd MMM yyyy hh:mm tt")
lblDate.Text     = $"Today is: {formatted}"

' Parsing a date from a string
Dim parsed As Date
If Date.TryParse(txtDate.Text, parsed) Then
    lblResult.Text = $"Valid date: {parsed:dd/MM/yyyy}"
Else
    lblResult.Text = "Invalid date entered."
End If
Try It — Simulation 8.2: Date Explorer

Enter a date, add days or months, and see formatted output — demonstrating VB 2026 Date arithmetic and formatting.

Date Explorer
Enter a Date (YYYY-MM-DD):
Add Days:
Format:
Results (lblDate):

8.5 Type Conversion

Converting between data types is a fundamental skill. VB 2026 provides two styles: implicit conversion (done automatically, widening only) and explicit conversion (using conversion functions or TryParse).

Widening vs Narrowing Conversions

FunctionConverts ToExampleThrows on Bad Input?
CInt()IntegerCInt("42") → 42✅ Yes
CLng()LongCLng("9000000000") → 9B✅ Yes
CDbl()DoubleCDbl("3.14") → 3.14✅ Yes
CDec()DecimalCDec("19.99") → 19.99D✅ Yes
CStr()StringCStr(42) → "42"❌ No
CBool()BooleanCBool(1) → True✅ Yes
CDate()DateCDate("Jan 1, 2026")✅ Yes
Integer.TryParse()Integer (safe)Returns Boolean❌ No — use this!
Double.TryParse()Double (safe)Returns Boolean❌ No — use this!

Example 8.1 — Safe Conversion with TryParse

Conversion.vb — Visual Basic 2026
' Unsafe — throws FormatException if user types "abc"
Dim bad = CInt(txtInput.Text)   ' ❌ avoid for user input

' Safe — TryParse returns True/False, never throws
Dim value As Integer
If Integer.TryParse(txtInput.Text, value) Then
    lblResult.Text = $"Valid integer: {value}"
Else
    lblResult.Text = "⚠ Please enter a whole number."
    lblResult.ForeColor = Color.Red
End If

' Double.TryParse — for decimal input
Dim amount As Double
If Double.TryParse(txtPrice.Text, amount) Then
    lblTotal.Text = $"Total: {amount * 1.06:F2}"
End If

' Converting number to string for display
Dim count  As Integer = 5
Dim msg    = $"You have {count} messages."   ' implicit String conversion in interpolation
Dim text   = count.ToString()                  ' explicit
Dim formatted = count.ToString("N0")          ' "5" with thousands separator
Try It — Simulation 8.3: Type Conversion Tester

Enter a value and choose a target type. See whether conversion succeeds or fails, and what VB 2026 code is used.

Type Conversion Tester
Input value (txtInput):
Convert To:
Conversion Result:

8.6 Overflow — When Values Are Too Large

Every numeric type has a fixed range. Trying to store a value outside that range causes an overflow error at runtime (if Option Strict On). Understanding ranges prevents this common bug.

Overflow.vb — Visual Basic 2026
' Byte max is 255 — going over causes OverflowException
Dim b As Byte = 255
b += 1  ' ❌ OverflowException at runtime!

' Integer max is 2,147,483,647
Dim n As Integer = Integer.MaxValue   ' 2,147,483,647
n += 1  ' ❌ OverflowException

' Solution 1 — use a bigger type (Long)
Dim safe As Long = Integer.MaxValue
safe += 1   ' ✅ 2,147,483,648 — no overflow

' Solution 2 — check before computing
If n < Integer.MaxValue Then
    n += 1
Else
    MsgBox("Value would overflow!")
End If

' Useful constants provided by .NET
Dim intMin = Integer.MinValue    ' -2,147,483,648
Dim intMax = Integer.MaxValue    '  2,147,483,647
Dim dblMax = Double.MaxValue     '  1.7976... × 10³⁰⁸
Try It — Simulation 8.4: Overflow Range Visualiser

Select a data type and enter a value. The bar shows where your value falls within the allowed range — red means overflow.

Overflow Range Visualiser
Data Type:
Enter a value:
Range

8.7 New in VB 2026 / .NET 10

Improved Type Inference

.NET 10 and VB 2026 significantly expand the compiler's ability to infer types from context, reducing boilerplate As Type annotations while keeping full type safety:

TypeInference.vb — Visual Basic 2026 / .NET 10
' Type inferred from literal value
Dim count    = 10          ' Integer
Dim price    = 9.99        ' Double
Dim name     = "Alice"     ' String
Dim flag     = True        ' Boolean

' Type inferred from method return value
Dim today    = DateTime.Today          ' Date
Dim items    = New List(Of String)()  ' List(Of String)

' Digit separators for readability (new in .NET 10)
Dim million  = 1_000_000
Dim pi       = 3.141_592_653_589_793
Dim binary   = &B1111_0000    ' binary literal = 240
Dim hex      = &HFF_FF        ' hex literal = 65535

' Nullable types — value OR Nothing
Dim maybeAge  As Integer? = Nothing   ' ? means nullable
If maybeAge.HasValue Then
    lblAge.Text = maybeAge.Value.ToString()
Else
    lblAge.Text = "Age not provided"
End If

' Null-coalescing — default if Nothing
Dim displayAge = maybeAge ?? 0      ' returns 0 if maybeAge is Nothing
🆕 Nullable Value Types in VB 2026

Adding ? after a value type makes it nullable — it can hold its normal values or Nothing. This is essential for database scenarios where a column value might be absent (NULL). Use .HasValue to test and .Value to read safely. The ?? null-coalescing operator provides a fallback value when the nullable is Nothing.


8.8 Choosing the Right Data Type

ScenarioBest TypeReason
Age, year, count, indexIntegerWhole number, fits in 4 bytes, fastest arithmetic
File size, row count > 2 billionLongWider range than Integer
Price, tax, salary, balanceDecimalExact base-10 arithmetic — no rounding errors
Scientific measurement, angle, ratioDouble15 sig digits, large exponent range
Name, address, message, codeStringUnicode text of any length
Yes/no flag, toggle, conditionBooleanTrue/False only — self-documenting
Birthday, deadline, timestampDateBuilt-in date arithmetic and formatting
Unknown type at compile timeObjectLast resort — loses type safety and IntelliSense

8.9 GitHub Copilot — Data Type Assistance

GitHub Copilot — Safe Conversion
You typed: ' Safely convert txtPrice to Decimal, show error in lblError if invalid, calculate total with 6% tax'
' Safely convert txtPrice to Decimal, show error in lblError if invalid, calculate total with 6% tax
Dim price As Decimal
If Decimal.TryParse(txtPrice.Text, price) Then
    Dim tax   = price * 0.06D
    Dim total = price + tax
    lblTotal.Text      = $"Price: {price:C}  Tax: {tax:C}  Total: {total:C}"
    lblError.Text      = ""
    lblError.ForeColor = Color.Black
Else
    lblError.Text      = "⚠ Please enter a valid price (e.g. 19.99)"
    lblError.ForeColor = Color.Red
End If
GitHub Copilot — Nullable Date
You typed: ' Try parse txtBirthday as a nullable Date, show age in years if valid, else show warning'
' Try parse txtBirthday as a nullable Date, show age in years if valid, else show warning
Dim birthday As Date? = Nothing
Dim parsed   As Date

If Date.TryParse(txtBirthday.Text, parsed) Then
    birthday = parsed
    Dim ageYears = (DateTime.Today - birthday.Value).TotalDays \ 365
    lblAge.Text = $"Age: {ageYears} years old"
Else
    lblAge.ForeColor = Color.OrangeRed
    lblAge.Text = "⚠ Invalid date — use YYYY-MM-DD format"
End If
💡 Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while working on data type problems:

  • "What data type should I use to store a Malaysian IC number like 900101-14-1234?"
  • "Convert all five TextBoxes on my form to Decimal, validate each one, and show a summary"
  • "Calculate how many days between two Date values and display in lblDays"
  • "Show the min and max values of Integer, Long, and Decimal in three Labels"
Try It — Simulation 8.5: Student Record — All Data Types

Fill in the form and click Save. Each field uses a different VB 2026 data type with validation.

Student Record Form
Name String
Age Integer
GPA Double
Fees (RM) Decimal
Enrolment Date Date
Active? Boolean

📘 Lesson Summary

  • Every variable has a data type determining its size, range, and valid operations. Choosing wrong wastes memory, causes overflow, or introduces rounding bugs.
  • Use Integer for whole numbers (age, count, index), Long when Integer's 2.1B limit could be exceeded, and Decimal for all money/financial values.
  • Use Double for scientific measurements — it stores ~15 significant digits but can have tiny binary rounding errors. Never use Double for money.
  • String is immutable Unicode text; use String.IsNullOrWhiteSpace() to safely check for empty/null strings.
  • Use AndAlso / OrElse (short-circuit) rather than And / Or — they skip the right operand when the result is already determined.
  • Date supports arithmetic via AddDays(), AddMonths(), subtraction returning TimeSpan, and formatting with ToString("format").
  • Prefer TryParse (Integer.TryParse, Double.TryParse, Date.TryParse) over CInt()/CDbl() for user input — TryParse never throws an exception.
  • In VB 2026 / .NET 10 use digit separators (1_000_000) for readability, nullable types (Integer?) for optional values, and ?? for null-safe defaults.
  • Type inference (Dim x = 42) lets the compiler deduce the type — use it for obvious cases; add explicit As Type when clarity matters.

Exercises

Exercise 8.1 — Data Type Salary Calculator

  • Create a form with TextBoxes for Employee Name (String), Hours Worked (Integer), and Hourly Rate (Decimal)
  • Calculate Gross Pay (Decimal = hours × rate), Tax at 11% (Decimal), and Net Pay (Decimal)
  • Display all results in Labels formatted as currency using :C format specifier
  • Validate all inputs with TryParse — show specific error messages per field if invalid
  • Copilot challenge: Ask Copilot to "add Overtime calculation: hours over 40 paid at 1.5× rate"

Exercise 8.2 — Date Countdown Timer

  • Add a DateTimePicker for the user to select a future event date
  • Calculate and display the number of days, hours, and minutes remaining until that date
  • Use Boolean to show different messages: "Event is today!" / "Event has passed" / "X days remaining"
  • Format the target date in three different formats using .ToString("format")
  • Copilot challenge: Ask Copilot to "add a Timer that updates the countdown every second"

Exercise 8.3 — Type Overflow Guard

  • Create TextBoxes for two numbers and a ComboBox to select Byte, Short, Integer, or Long
  • When the user clicks Add, perform the addition and detect if the result would overflow the selected type
  • Use Integer.MaxValue, Short.MaxValue, etc. to check before computing
  • Show the result in green if safe, or a red overflow warning if not, and suggest upgrading to the next type
  • Copilot challenge: Ask Copilot to "add Multiply and Subtract operations with the same overflow detection"

Next: Lesson 9 — Variables and Constants

Learn how to declare variables using Dim, scope rules (local, form-level, module-level), naming conventions, and how to define constants with Const for values that never change.

Continue ❯

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Comprehensive coverage of all VB.NET data types, variables, constants, and type conversion with practical examples.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 complete VB.NET programs illustrating proper use of data types in real-world applications including calculators, converters, and record forms.

View on Amazon →