MSDN Documentation

Variables and Data Types in VB.NET

In VB.NET, a variable is a symbolic name given to a storage location in memory that can be used to store a value of a particular data type. Variables are essential for holding and manipulating data within your programs.

Declaring Variables

You declare a variable using the Dim keyword, followed by the variable name, the As keyword, and then the data type.


Dim age As Integer
Dim name As String
Dim isComplete As Boolean
Dim price As Decimal
            

Data Types

VB.NET provides a rich set of built-in data types to represent different kinds of information. Choosing the correct data type is crucial for efficient memory usage and accurate data manipulation.

Numeric Data Types

Character and String Data Types

Boolean Data Type

Date and Time Data Type

Object Data Type

Variable Initialization

You can initialize a variable at the time of declaration or later.


' Initialization at declaration
Dim count As Integer = 10
Dim message As String = "Hello, VB.NET!"

' Initialization after declaration
Dim pi As Double
pi = 3.14159
            

Type Inference (Option Infer)

When Option Infer On is enabled (which is the default in modern VB.NET projects), the compiler can infer the data type of a variable from the value assigned to it.


' With Option Infer On, the compiler knows 'x' is an Integer
Dim x = 5

' And 'greeting' is a String
Dim greeting = "Welcome"
            
Note: While type inference is convenient, explicitly declaring data types can sometimes improve code clarity and prevent unexpected behavior.

Implicit vs. Explicit Conversions

VB.NET supports both implicit (widening) and explicit (narrowing) type conversions.

Example of Conversion


Dim smallNumber As Integer = 100
Dim largeNumber As Long

' Implicit conversion
largeNumber = smallNumber ' OK

Dim numberString As String = "123"
Dim convertedNumber As Integer

' Explicit conversion
convertedNumber = CInt(numberString) ' OK
                

Scope of Variables

The scope of a variable determines where in your code it can be accessed. Common scopes include:

Understanding variables and data types is fundamental to programming in VB.NET. Mastering these concepts will allow you to store, manage, and manipulate data effectively in your applications.