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.
8.1 The Two Main Categories
VB 2026 divides all data types into two broad categories:
- Value Types — store data directly in memory (stack). Includes all numeric types, Boolean, Date, Char, and Structure. Fast access, fixed size.
- Reference Types — store a reference (pointer) to data on the heap. Includes String, Object, arrays, and Class instances. Can be
Nothing.
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.
' 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 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.
Enter a number and select a data type. See whether the value fits, its memory size, and the VB 2026 declaration syntax.
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.
' 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.
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 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.
' 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
Enter a date, add days or months, and see formatted output — demonstrating VB 2026 Date arithmetic and formatting.
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
- Widening — converting to a larger type (safe, automatic):
Integer → Long → Double - Narrowing — converting to a smaller type (possible data loss, requires explicit call):
Double → Integer
| Function | Converts To | Example | Throws on Bad Input? |
|---|---|---|---|
| CInt() | Integer | CInt("42") → 42 | ✅ Yes |
| CLng() | Long | CLng("9000000000") → 9B | ✅ Yes |
| CDbl() | Double | CDbl("3.14") → 3.14 | ✅ Yes |
| CDec() | Decimal | CDec("19.99") → 19.99D | ✅ Yes |
| CStr() | String | CStr(42) → "42" | ❌ No |
| CBool() | Boolean | CBool(1) → True | ✅ Yes |
| CDate() | Date | CDate("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
' 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
Enter a value and choose a target type. See whether conversion succeeds or fails, and what VB 2026 code is used.
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.
' 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³⁰⁸
Select a data type and enter a value. The bar shows where your value falls within the allowed range — red means overflow.
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:
' 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
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
| Scenario | Best Type | Reason |
|---|---|---|
| Age, year, count, index | Integer | Whole number, fits in 4 bytes, fastest arithmetic |
| File size, row count > 2 billion | Long | Wider range than Integer |
| Price, tax, salary, balance | Decimal | Exact base-10 arithmetic — no rounding errors |
| Scientific measurement, angle, ratio | Double | 15 sig digits, large exponent range |
| Name, address, message, code | String | Unicode text of any length |
| Yes/no flag, toggle, condition | Boolean | True/False only — self-documenting |
| Birthday, deadline, timestamp | Date | Built-in date arithmetic and formatting |
| Unknown type at compile time | Object | Last resort — loses type safety and IntelliSense |
8.9 GitHub Copilot — Data Type Assistance
' 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
' 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
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"
Fill in the form and click Save. Each field uses a different VB 2026 data type with validation.
📘 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 thanAnd/Or— they skip the right operand when the result is already determined. - Date supports arithmetic via
AddDays(),AddMonths(), subtraction returningTimeSpan, and formatting withToString("format"). - Prefer TryParse (
Integer.TryParse,Double.TryParse,Date.TryParse) overCInt()/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 explicitAs Typewhen 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
:Cformat 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"
Related Resources
← Lesson 7
PictureBox — loading, displaying, and manipulating images.
Lesson 9 →
Variables & Constants — Dim, scope, naming rules, Const.
MS Docs — Data Types
Official Microsoft reference for all VB.NET data types and conversions.
Conversion Functions
Full reference for CInt, CDbl, CStr, TryParse and all conversion functions.
Featured Books
Visual Basic 2022 Made Easy
Comprehensive coverage of all VB.NET data types, variables, constants, and type conversion with practical examples.
View on Amazon →
VB Programming With Code Examples
48 complete VB.NET programs illustrating proper use of data types in real-world applications including calculators, converters, and record forms.
View on Amazon →