Data Types. Simple and Complex, Conversion, Nullable, Float, Generic
Data Types. Simple and Complex, Conversion, Nullable, Float, Generic
aspx
The data type of a programming element refers to what kind of data it can hold and how it stores that data. Data types
apply to all values that can be stored in computer memory or participate in the evaluation of an expression. Every variable,
literal, constant, enumeration, property, procedure parameter, procedure argument, and procedure return value has a data
type.
Programming
Data type declaration
element
Literal With a literal type character; see "Literal Type Characters" in Type Characters (Visual Basic)
Procedure In a Sub Statement (Visual Basic), Function Statement (Visual Basic), or Operator Statement
parameter
Sub addSale(ByVal amount As Double)
1 of 2 02.09.2016 17:08
Data Types in Visual Basic https://msdn.microsoft.com/en-us/library/ffsdktda(d=printer).aspx
Procedure argument In the calling code; each argument is a programming element that has already been declared,
or an expression containing declared elements
For a list of Visual Basic data types, see Data Type Summary (Visual Basic).
See Also
Type Characters (Visual Basic)
Elementary Data Types (Visual Basic)
Composite Data Types (Visual Basic)
Generic Types in Visual Basic (Visual Basic)
Value Types and Reference Types
Type Conversions in Visual Basic
Structures (Visual Basic)
Troubleshooting Data Types (Visual Basic)
Data Type Summary (Visual Basic)
Efficient Use of Data Types (Visual Basic)
© 2016 Microsoft
2 of 2 02.09.2016 17:08
Troubleshooting Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae382yt8(d=printer).aspx
This page lists some common problems that can occur when you perform operations on intrinsic data types.
Because of this imprecision, you cannot rely on exact results when you operate on floating-point values. In particular, two
values that are theoretically equal might have slightly different representations.
1. Calculate the absolute value of their difference by using the Abs method of the Math class in the System
namespace.
2. Determine an acceptable maximum difference, such that you can consider the two quantities to be equal for
practical purposes if their difference is no larger.
3. Compare the absolute value of the difference to the acceptable difference.
The following example demonstrates both incorrect and correct comparison of two Double values.
VB
1 of 5 02.09.2016 17:23
Troubleshooting Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae382yt8(d=printer).aspx
CStr(practicallyEqual))
The previous example uses the ToString method of the Double structure so that it can specify better precision than the
CStr keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
The Decimal Data Type (Visual Basic) does not use floating-point representation. Many numbers that are inexact in Single
and Double are exact in Decimal (for example 0.2 and 0.3). Although arithmetic is slower in Decimal than in floating-
point, it might be worth the performance decrease to achieve better precision.
VB
The previous example uses the ToString method of the Double structure so that it can specify better precision than the
CStr keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
Because zeroPointTwo is Double, its value for 0.2 is an infinitely repeating binary fraction with a stored value of
0.20000000000000001. Dividing 2.0 by this quantity yields 9.9999999999999995 with a remainder of
0.19999999999999991.
In the expression for decimalRemainder, the literal type character D forces both operands to Decimal, and 0.2 has a
2 of 5 02.09.2016 17:23
Troubleshooting Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae382yt8(d=printer).aspx
precise representation. Therefore the Mod operator yields the expected remainder of 0.0.
Note that it is not sufficient to declare decimalRemainder as Decimal. You must also force the literals to Decimal, or
they use Double by default and decimalRemainder receives the same inaccurate value as doubleRemainder.
You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should
restrict usage of Boolean variables to the logical values for which they are designed. If you must mix Boolean and
numeric values, make sure that you understand the conversion method that you select.
If you must convert a Boolean value to a numeric data type, be careful about which conversion method you use.
The String data type does not widen to the Char Data Type (Visual Basic). This means that if you want to assign a literal to
a Char variable, you must either make a narrowing conversion or force the literal to the Char type.
3 of 5 02.09.2016 17:23
Troubleshooting Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae382yt8(d=printer).aspx
The following example demonstrates both unsuccessful and successful assignments of a literal to a Char variable.
VB
There is always a risk in using narrowing conversions, because they can fail at run time. For example, a conversion from
String to Char can fail if the String value contains more than one character. Therefore, it is better programming to use
the C type character.
When the type checking switch (Option Strict Statement) is On, the compiler disallows all implicit narrowing conversions.
This includes those involving String. Your code can still use conversion keywords such as CStr and CType Function (Visual
Basic), which direct the .NET Framework to attempt the conversion.
Note
The narrowing-conversion error is suppressed for conversions from the elements in a For Each…Next collection to the
loop control variable. For more information and examples, see the "Narrowing Conversions" section in For Each...Next
Statement (Visual Basic).
If you must convert from String to another data type, the safest procedure is to enclose the attempted conversion in
4 of 5 02.09.2016 17:23
Troubleshooting Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae382yt8(d=printer).aspx
the Try...Catch...Finally Statement (Visual Basic). This lets you deal with a run-time failure.
Character Arrays
A single Char and an array of Char elements both widen to String. However, String does not widen to Char(). To
convert a String value to a Char array, you can use the ToCharArray method of the System.String class.
Meaningless Values
In general, String values are not meaningful in other data types, and conversion is highly artificial and dangerous.
Whenever possible, you should restrict usage of String variables to the character sequences for which they are
designed. You should never write code that relies on equivalent values in other types.
See Also
Data Types in Visual Basic
Type Characters (Visual Basic)
Value Types and Reference Types
Type Conversions in Visual Basic
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
Efficient Use of Data Types (Visual Basic)
© 2016 Microsoft
5 of 5 02.09.2016 17:23
Data Type Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/47zceaw7(d=printer).aspx
The following table shows the Visual Basic data types, their supporting common language runtime types, their nominal
storage allocation, and their value ranges.
Common
Nominal
Visual Basic language
storage Value range
type runtime type
allocation
structure
Object Object (class) 4 bytes on Any type can be stored in a variable of type Object
1 of 3 02.09.2016 17:08
Data Type Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/47zceaw7(d=printer).aspx
32-bit platform
8 bytes on
64-bit platform
User-Defined (inherits from Depends on Each member of the structure has a range determined by its
(structure) ValueType) implementing data type and independent of the ranges of the other
platform members
† In scientific notation, "E" refers to a power of 10. So 3.56E+2 signifies 3.56 x 102 or 356, and 3.56E-2 signifies 3.56 / 102 or
0.0356.
Note
For strings containing text, use the StrConv function to convert from one text format to another.
In addition to specifying a data type in a declaration statement, you can force the data type of some programming elements
by using a type character. See Type Characters (Visual Basic).
Memory Consumption
When you declare an elementary data type, it is not safe to assume that its memory consumption is the same as its
nominal storage allocation. This is due to the following considerations:
Storage Assignment. The common language runtime can assign storage based on the current characteristics of
2 of 3 02.09.2016 17:08
Data Type Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/47zceaw7(d=printer).aspx
the platform on which your application is executing. If memory is nearly full, it might pack your declared elements
as closely together as possible. In other cases it might align their memory addresses to natural hardware
boundaries to optimize performance.
Platform Width. Storage assignment on a 64-bit platform is different from assignment on a 32-bit platform.
Overhead. Some composite types have additional memory requirements. For example, an array uses extra
memory for the array itself and also for each dimension. On a 32-bit platform, this overhead is currently 12
bytes plus 8 bytes for each dimension. On a 64-bit platform this requirement is doubled.
Storage Layout. You cannot safely assume that the order of storage in memory is the same as your order of
declaration. You cannot even make assumptions about byte alignment, such as a 2-byte or 4-byte boundary. If
you are defining a class or structure and you need to control the storage layout of its members, you can apply
the StructLayoutAttribute attribute to the class or structure.
Object Overhead
An Object referring to any elementary or composite data type uses 4 bytes in addition to the data contained in the
data type.
See Also
StrConv
StructLayoutAttribute
Type Conversion Functions (Visual Basic)
Conversion Summary (Visual Basic)
Type Characters (Visual Basic)
Efficient Use of Data Types (Visual Basic)
© 2016 Microsoft
3 of 3 02.09.2016 17:08
Numeric Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae55hdtk(d=printer).aspx
Visual Basic supplies several numeric data types for handling numbers in various representations. Integral types represent
only whole numbers (positive, negative, and zero), and nonintegral types represent numbers with both integer and fractional
parts.
For a table showing a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
The signed integral data types are SByte Data Type (Visual Basic) (8-bit), Short Data Type (Visual Basic) (16-bit), Integer
Data Type (Visual Basic) (32-bit), and Long Data Type (Visual Basic) (64-bit). If a variable always stores integers rather than
fractional numbers, declare it as one of these types.
The unsigned integral types are Byte Data Type (Visual Basic) (8-bit), UShort Data Type (Visual Basic) (16-bit), UInteger
Data Type (32-bit), and ULong Data Type (Visual Basic) (64-bit). If a variable contains binary data, or data of unknown
nature, declare it as one of these types.
Performance
Arithmetic operations are faster with integral types than with other data types. They are fastest with the Integer and
UInteger types in Visual Basic.
Large Integers
If you need to hold an integer larger than the Integer data type can hold, you can use the Long data type instead.
Long variables can hold numbers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Operations
with Long are slightly slower than with Integer.
If you need even larger values, you can use the Decimal Data Type (Visual Basic). You can hold numbers from
-79,228,162,514,264,337,593,543,950,335 through 79,228,162,514,264,337,593,543,950,335 in a Decimal variable if
you do not use any decimal places. However, operations with Decimal numbers are considerably slower than with any
other numeric data type.
Small Integers
1 of 3 02.09.2016 17:10
Numeric Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae55hdtk(d=printer).aspx
If you do not need the full range of the Integer data type, you can use the Short data type, which can hold integers
from -32,768 through 32,767. For the smallest integer range, the SByte data type holds integers from -128 through
127. If you have a very large number of variables that hold small integers, the common language runtime can
sometimes store your Short and SByte variables more efficiently and save memory consumption. However, operations
with Short and SByte are somewhat slower than with Integer.
Unsigned Integers
If you know that your variable never needs to hold a negative number, you can use the unsigned types Byte, UShort,
UInteger, and ULong. Each of these data types can hold a positive integer twice as large as its corresponding signed
type (SByte, Short, Integer, and Long). In terms of performance, each unsigned type is exactly as efficient as its
corresponding signed type. In particular, UInteger shares with Integer the distinction of being the most efficient of all
the elementary numeric data types.
The nonintegral numeric data types are Decimal (128-bit fixed point), Single Data Type (Visual Basic) (32-bit floating
point), and Double Data Type (Visual Basic) (64-bit floating point). They are all signed types. If a variable can contain a
fraction, declare it as one of these types.
Decimal is not a floating-point data type. Decimal numbers have a binary integer value and an integer scaling factor
that specifies what portion of the value is a decimal fraction.
You can use Decimal variables for money values. The advantage is the precision of the values. The Double data type is
faster and requires less memory, but it is subject to rounding errors. The Decimal data type retains complete accuracy to
28 decimal places.
Floating-point (Single and Double) numbers have larger ranges than Decimal numbers but can be subject to rounding
errors. Floating-point types support fewer significant digits than Decimal but can represent values of greater magnitude.
Nonintegral number values can be expressed as mmmEeee, in which mmm is the mantissa (the significant digits) and eee
is the exponent (a power of 10). The highest positive values of the nonintegral types are
7.9228162514264337593543950335E+28 for Decimal, 3.4028235E+38 for Single, and 1.79769313486231570E+308 for
Double.
Performance
Double is the most efficient of the fractional data types, because the processors on current platforms perform
floating-point operations in double precision. However, operations with Double are not as fast as with the integral
types such as Integer.
Small Magnitudes
For numbers with the smallest possible magnitude (closest to 0), Double variables can hold numbers as small as
2 of 3 02.09.2016 17:10
Numeric Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ae55hdtk(d=printer).aspx
See Also
Elementary Data Types (Visual Basic)
Character Data Types (Visual Basic)
Miscellaneous Data Types (Visual Basic)
Troubleshooting Data Types (Visual Basic)
How to: Call a Windows Function that Takes Unsigned Types (Visual Basic)
© 2016 Microsoft
3 of 3 02.09.2016 17:10
Character Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/25sb10we(d=printer).aspx
Visual Basic provides character data types to deal with printable and displayable characters. While they both deal with
Unicode characters, Char holds a single character whereas String contains an indefinite number of characters.
For a table that displays a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
Char Type
The Char data type is a single two-byte (16-bit) Unicode character. If a variable always stores exactly one character,
declare it as Char. For example:
VB
Each possible value in a Char or String variable is a code point, or character code, in the Unicode character set. Unicode
characters include the basic ASCII character set, various other alphabet letters, accents, currency symbols, fractions,
diacritics, and mathematical and technical symbols.
Note
The Unicode character set reserves the code points D800 through DFFF (55296 through 55551 decimal) for surrogate
pairs, which require two 16-bit values to represent a single code point. A Char variable cannot hold a surrogate pair,
and a String uses two positions to hold such a pair.
String Type
1 of 2 02.09.2016 17:10
Character Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/25sb10we(d=printer).aspx
The String data type is a sequence of zero or more two-byte (16-bit) Unicode characters. If a variable can contain an
indefinite number of characters, declare it as String. For example:
VB
See Also
Elementary Data Types (Visual Basic)
Composite Data Types (Visual Basic)
Generic Types in Visual Basic (Visual Basic)
Value Types and Reference Types
Type Conversions in Visual Basic
Troubleshooting Data Types (Visual Basic)
Type Characters (Visual Basic)
© 2016 Microsoft
2 of 2 02.09.2016 17:10
Miscellaneous Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/y71y6066(d=printer).aspx
Visual Basic supplies several data types that are not oriented toward numbers or characters. Instead, they deal with
specialized data such as yes/no values, date/time values, and object addresses.
For a table showing a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
Boolean Type
The Boolean Data Type (Visual Basic) is an unsigned value that is interpreted as either True or False. Its data width
depends on the implementing platform. If a variable can contain only two-state values such as true/false, yes/no, or
on/off, declare it as Boolean.
Date Type
The Date Data Type (Visual Basic) is a 64-bit value that holds both date and time information. Each increment represents
100 nanoseconds of elapsed time since the beginning (12:00 AM) of January 1 of the year 1 in the Gregorian calendar. If a
variable can contain a date value, a time value, or both, declare it as Date.
Object Type
The Object Data Type is a 32-bit address that points to an object instance within your application or in some other
application. An Object variable can refer to any object your application recognizes, or to data of any data type. This
includes both value types, such as Integer, Boolean, and structure instances, and reference types, which are instances of
objects created from classes such as String and Form, and array instances.
If a variable stores a pointer to an instance of a class that you do not know at compile time, or if it can point to data of
various data types, declare it as Object.
The advantage of the Object data type is that you can use it to store data of any data type. The disadvantage is that you
incur extra operations that take more execution time and make your application perform slower. If you use an Object
variable for value types, you incur boxing and unboxing. If you use it for reference types, you incur late binding.
See Also
Type Characters (Visual Basic)
Elementary Data Types (Visual Basic)
Numeric Data Types (Visual Basic)
Character Data Types (Visual Basic)
Troubleshooting Data Types (Visual Basic)
1 of 2 02.09.2016 17:09
Miscellaneous Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/y71y6066(d=printer).aspx
© 2016 Microsoft
2 of 2 02.09.2016 17:09
Conversion Summary (Visual Basic) https://msdn.microsoft.com/en-us/library/ewf8xx62(d=printer).aspx
Visual Basic language keywords and run-time library members are organized by purpose and use.
Convert one data type to another. CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CShort, CStr, CType,
Fix, Int
See Also
Keywords (Visual Basic)
Visual Basic Runtime Library Members
© 2016 Microsoft
1 of 1 02.09.2016 17:11
Composite Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/d682h20d(d=printer).aspx
In addition to the elementary data types Visual Basic supplies, you can also assemble items of different types to create
composite data types such as structures, arrays, and classes. You can build composite data types from elementary types and
from other composite types. For example, you can define an array of structure elements, or a structure with array members.
Data Types
A composite type is different from the data type of any of its components. For example, an array of Integer elements is
not of the Integer data type.
An array data type is normally represented using the element type, parentheses, and commas as necessary. For example, a
one-dimensional array of String elements is represented as String(), and a two-dimensional array of Boolean elements is
represented as Boolean(,).
Structure Types
There is no single data type comprising all structures. Instead, each definition of a structure represents a unique data type,
even if two structures define identical elements in the same order. However, if you create two or more instances of the
same structure, Visual Basic considers them to be of the same data type.
Array Types
There is no single data type comprising all arrays. The data type of a particular instance of an array is determined by the
following:
In particular, the length of a given dimension is not part of the instance's data type. The following example illustrates this.
1 of 2 02.09.2016 17:11
Composite Data Types (Visual Basic) https://msdn.microsoft.com/en-us/library/d682h20d(d=printer).aspx
In the preceding example, array variables arrayA and arrayB are considered to be of the same data type — Byte() —
even though they are initialized to different lengths. Variables arrayB and arrayC are not of the same type because their
element types are different. Variables arrayC and arrayD are not of the same type because their ranks are different.
Variables arrayD and arrayE have the same type — Short(,) — because their ranks and element types are the same,
even though arrayD is not yet initialized.
Class Types
There is no single data type comprising all classes. Although one class can inherit from another class, each is a separate
data type. Multiple instances of the same class are of the same data type. If you assign one class instance variable to
another, not only do they have the same data type, they point to the same class instance in memory.
For more information on classes, see Objects and Classes in Visual Basic.
See Also
Data Types in Visual Basic
Elementary Data Types (Visual Basic)
Generic Types in Visual Basic (Visual Basic)
Value Types and Reference Types
Type Conversions in Visual Basic
Structures (Visual Basic)
Troubleshooting Data Types (Visual Basic)
How to: Hold More Than One Value in a Variable (Visual Basic)
© 2016 Microsoft
2 of 2 02.09.2016 17:11
How to: Hold More Than One Value in a Variable (Visual Basic) https://msdn.microsoft.com/en-us/library/axdeky2x(d=printer).aspx
A variable holds more than one value if you declare it to be of a composite data type.
Composite Data Types (Visual Basic) include structures, arrays, and classes. A variable of a composite data type can hold a
combination of elementary data types and other composite types. Structures and classes can hold code as well as data.
2. If the composite data type is not already defined, define it so that your variable can use it.
5. Follow the As keyword with the name of the appropriate composite data type.
See Also
Data Type Summary (Visual Basic)
Type Characters (Visual Basic)
Composite Data Types (Visual Basic)
Structures (Visual Basic)
Arrays in Visual Basic
Objects and Classes in Visual Basic
Value Types and Reference Types
© 2016 Microsoft
1 of 1 02.09.2016 17:12
Generic Types in Visual Basic (Visual Basic) https://msdn.microsoft.com/en-us/library/w256ka79(d=printer).aspx
A generic type is a single programming element that adapts to perform the same functionality for a variety of data types.
When you define a generic class or procedure, you do not have to define a separate version for each data type for which you
might want to perform that functionality.
An analogy is a screwdriver set with removable heads. You inspect the screw you need to turn and select the correct head for
that screw (slotted, crossed, starred). Once you insert the correct head in the screwdriver handle, you perform the exact same
function with the screwdriver, namely turning the screw.
When you define a generic type, you parameterize it with one or more data types. This allows the using code to tailor the
data types to its requirements. Your code can declare several different programming elements from the generic element,
each one acting on a different set of data types. But the declared elements all perform the identical logic, no matter what
data types they are using.
For example, you might want to create and use a queue class that operates on a specific data type such as String. You can
declare such a class from System.Collections.Generic.Queue(Of T), as the following example shows.
VB
You can now use stringQ to work exclusively with String values. Because stringQ is specific for String instead of being
generalized for Object values, you do not have late binding or type conversion. This saves execution time and reduces
run-time errors.
For more information on using a generic type, see How to: Use a Generic Class (Visual Basic).
1 of 5 02.09.2016 17:13
Generic Types in Visual Basic (Visual Basic) https://msdn.microsoft.com/en-us/library/w256ka79(d=printer).aspx
VB
In the preceding skeleton, t is a type parameter, that is, a placeholder for a data type that you supply when you declare
the class. Elsewhere in your code, you can declare various versions of classHolder by supplying various data types for t.
The following example shows two such declarations.
VB
The preceding statements declare constructed classes, in which a specific type replaces the type parameter. This
replacement is propagated throughout the code within the constructed class. The following example shows what the
processNewItem procedure looks like in integerClass.
VB
For a more complete example, see How to: Define a Class That Can Provide Identical Functionality on Different Data Types
(Visual Basic).
Procedures are not types, but you can define and use generic procedures. See Generic Procedures in Visual Basic.
2 of 5 02.09.2016 17:13
Generic Types in Visual Basic (Visual Basic) https://msdn.microsoft.com/en-us/library/w256ka79(d=printer).aspx
2. A set of type-specific versions of the type, each version individually coded and operating on one specific data type
such as String, Integer, or a user-defined type such as customer.
Type Safety. Generic types enforce compile-time type checking. Types based on Object accept any data type, and
you must write code to check whether an input data type is acceptable. With generic types, the compiler can catch
type mismatches before run time.
Performance. Generic types do not have to box and unbox data, because each one is specialized for one data
type. Operations based on Object must box input data types to convert them to Object and unbox data destined
for output. Boxing and unboxing reduce performance.
Types based on Object are also late-bound, which means that accessing their members requires extra code at run
time. This also reduces performance.
Code Consolidation. The code in a generic type has to be defined only once. A set of type-specific versions of a
type must replicate the same code in each version, with the only difference being the specific data type for that
version. With generic types, the type-specific versions are all generated from the original generic type.
Code Reuse. Code that does not depend on a particular data type can be reused with various data types if it is
generic. You can often reuse it even with a data type that you did not originally predict.
IDE Support. When you use a constructed type declared from a generic type, the integrated development
environment (IDE) can give you more support while you are developing your code. For example, IntelliSense can
show you the type-specific options for an argument to a constructor or method.
Generic Algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For
example, a generic procedure that sorts items using the IComparable interface can be used with any data type that
implements IComparable.
Constraints
Although the code in a generic type definition should be as type-independent as possible, you might need to require a
certain capability of any data type supplied to your generic type. For example, if you want to compare two items for the
purpose of sorting or collating, their data type must implement the IComparable interface. You can enforce this
requirement by adding a constraint to the type parameter.
Example of a Constraint
The following example shows a skeleton definition of a class with a constraint that requires the type argument to
implement IComparable.
VB
3 of 5 02.09.2016 17:13
Generic Types in Visual Basic (Visual Basic) https://msdn.microsoft.com/en-us/library/w256ka79(d=printer).aspx
End Class
If subsequent code attempts to construct a class from itemManager supplying a type that does not implement
IComparable, the compiler signals an error.
Types of Constraints
Your constraint can specify the following requirements in any combination:
The type argument must be of the type of, or inherit from, at most one class
The type argument must expose a parameterless constructor accessible to the code that creates objects from it
If you need to impose more than one requirement, you use a comma-separated constraint list inside braces ({ }). To
require an accessible constructor, you include the New Operator (Visual Basic) keyword in the list. To require a reference
type, you include the Class keyword; to require a value type, you include the Structure keyword.
VB
Important Terms
Generic types introduce and use the following terms:
Generic Type. A definition of a class, structure, interface, procedure, or delegate for which you supply at least one
data type when you declare it.
Type Parameter. In a generic type definition, a placeholder for a data type you supply when you declare the type.
Type Argument. A specific data type that replaces a type parameter when you declare a constructed type from a
4 of 5 02.09.2016 17:13
Generic Types in Visual Basic (Visual Basic) https://msdn.microsoft.com/en-us/library/w256ka79(d=printer).aspx
generic type.
Constraint. A condition on a type parameter that restricts the type argument you can supply for it. A constraint can
require that the type argument must implement a particular interface, be or inherit from a particular class, have an
accessible parameterless constructor, or be a reference type or a value type. You can combine these constraints,
but you can specify at most one class.
Constructed Type. A class, structure, interface, procedure, or delegate declared from a generic type by supplying
type arguments for its type parameters.
See Also
Data Types in Visual Basic
Type Characters (Visual Basic)
Value Types and Reference Types
Type Conversions in Visual Basic
Troubleshooting Data Types (Visual Basic)
Data Type Summary (Visual Basic)
Of Clause (Visual Basic)
As
Object Data Type
Covariance and Contravariance (C# and Visual Basic)
Iterators (C# and Visual Basic)
© 2016 Microsoft
5 of 5 02.09.2016 17:13
How to: Define a Class That Can Provide Identical Functionality on Differ... https://msdn.microsoft.com/en-us/library/4a1b71ta(d=printer).aspx
You can define a class from which you can create objects that provide identical functionality on different data types. To do
this, you specify one or more type parameters in the definition. The class can then serve as a template for objects that use
various data types. A class defined in this way is called a generic class.
The advantage of defining a generic class is that you define it just once, and your code can use it to create many objects that
use a wide variety of data types. This results in better performance than defining the class with the Object type.
In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.
2. Add (Of typeparameter) immediately after the class name to specify a type parameter.
3. If you have more than one type parameter, make a comma-separated list inside the parentheses. Do not repeat the
Of keyword.
4. If your code performs operations on a type parameter other than simple assignment, follow that type parameter with
an As clause to add one or more constraints. A constraint guarantees that the type supplied for that type parameter
satisfies a requirement such as the following:
If you do not specify any constraints, the only operations and members your code can use are those supported by the
Object Data Type. For more information, see Type List (Visual Basic).
5. Identify every class member that is to be declared with a supplied type, and declare it As typeparameter. This applies
to internal storage, procedure parameters, and return values.
6. Be sure your code uses only operations and methods that are supported by any data type it can supply to itemType.
The following example defines a class that manages a very simple list. It holds the list in the internal array items, and
the using code can declare the data type of the list elements. A parameterized constructor allows the using code to
set the upper bound of items, and the default constructor sets this to 9 (for a total of 10 items).
VB
1 of 4 02.09.2016 17:14
How to: Define a Class That Can Provide Identical Functionality on Differ... https://msdn.microsoft.com/en-us/library/4a1b71ta(d=printer).aspx
2 of 4 02.09.2016 17:14
How to: Define a Class That Can Provide Identical Functionality on Differ... https://msdn.microsoft.com/en-us/library/4a1b71ta(d=printer).aspx
You can declare a class from simpleList to hold a list of Integer values, another class to hold a list of String values,
and another to hold Date values. Except for the data type of the list members, objects created from all these classes
behave identically.
The type argument that the using code supplies to itemType can be an intrinsic type such as Boolean or Double, a
structure, an enumeration, or any type of class, including one that your application defines.
You can test the class simpleList with the following code.
VB
3 of 4 02.09.2016 17:14
How to: Define a Class That Can Provide Identical Functionality on Differ... https://msdn.microsoft.com/en-us/library/4a1b71ta(d=printer).aspx
End Sub
See Also
Data Types in Visual Basic
Generic Types in Visual Basic (Visual Basic)
Language Independence and Language-Independent Components
Of Clause (Visual Basic)
Type List (Visual Basic)
How to: Use a Generic Class (Visual Basic)
Object Data Type
© 2016 Microsoft
4 of 4 02.09.2016 17:14
How to: Use a Generic Class (Visual Basic) https://msdn.microsoft.com/en-us/library/79btc5zc(d=printer).aspx
A class that takes type parameters is called a generic class. If you are using a generic class, you can generate a constructed
class from it by supplying a type argument for each of these parameters. You can then declare a variable of the constructed
class type, and you can create an instance of the constructed class and assign it to that variable.
In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.
The following procedure takes a generic class defined in the .NET Framework and creates an instance from it.
2. Create the object in the normal way, but add (Of type) immediately after the class name.
The following example uses the same class (System.Collections.Generic.Queue(Of T)) to create two queue objects that
hold items of different data types. It adds items to the end of each queue and then removes and displays items from
the front of each queue.
VB
1 of 2 02.09.2016 17:15
How to: Use a Generic Class (Visual Basic) https://msdn.microsoft.com/en-us/library/79btc5zc(d=printer).aspx
See Also
Data Types in Visual Basic
Generic Types in Visual Basic (Visual Basic)
Language Independence and Language-Independent Components
Of Clause (Visual Basic)
Imports Statement (.NET Namespace and Type)
How to: Define a Class That Can Provide Identical Functionality on Different Data Types (Visual Basic)
Iterators (C# and Visual Basic)
© 2016 Microsoft
2 of 2 02.09.2016 17:15
Generic Procedures in Visual Basic https://msdn.microsoft.com/en-us/library/ms235246(d=printer).aspx
A generic procedure, also called a generic method, is a procedure defined with at least one type parameter. This allows the
calling code to tailor the data types to its requirements each time it calls the procedure.
A procedure is not generic simply by virtue of being defined inside a generic class or a generic structure. To be generic, the
procedure must take at least one type parameter, in addition to any normal parameters it might take. A generic class or
structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures.
A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its
procedure code.
Type Inference
You can call a generic procedure without supplying any type arguments at all. If you call it this way, the compiler attempts
to determine the appropriate data types to pass to the procedure's type arguments. This is called type inference. The
following code shows a call in which the compiler infers that it should pass type String to the type parameter t.
VB
If the compiler cannot infer the type arguments from the context of your call, it reports an error. One possible cause of
such an error is an array rank mismatch. For example, suppose you define a normal parameter as an array of a type
parameter. If you call the generic procedure supplying an array of a different rank (number of dimensions), the mismatch
causes type inference to fail. The following code shows a call in which a two-dimensional array is passed to a procedure
that expects a one-dimensional array.
End Sub
demoSub(twoDimensions)
End Sub
You can invoke type inference only by omitting all the type arguments. If you supply one type argument, you must supply
them all.
1 of 3 02.09.2016 17:16
Generic Procedures in Visual Basic https://msdn.microsoft.com/en-us/library/ms235246(d=printer).aspx
Type inference is supported only for generic procedures. You cannot invoke type inference on generic classes, structures,
interfaces, or delegates.
Example
Description
The following example defines a generic Function procedure to find a particular element in an array. It defines one
type parameter and uses it to construct the two parameters in the parameter list.
Code
VB
Return ‐1
End Function
Comments
The preceding example requires the ability to compare searchValue against each element of searchArray. To
guarantee this ability, it constrains the type parameter T to implement the IComparable(Of T) interface. The code uses
the CompareTo method instead of the = operator, because there is no guarantee that a type argument supplied for T
supports the = operator.
You can test the findElement procedure with the following code.
VB
2 of 3 02.09.2016 17:16
Generic Procedures in Visual Basic https://msdn.microsoft.com/en-us/library/ms235246(d=printer).aspx
The preceding calls to MsgBox display "0", "1", and "-1" respectively.
See Also
Generic Types in Visual Basic (Visual Basic)
How to: Define a Class That Can Provide Identical Functionality on Different Data Types (Visual Basic)
How to: Use a Generic Class (Visual Basic)
Procedures in Visual Basic
Procedure Parameters and Arguments (Visual Basic)
Type List (Visual Basic)
Parameter List (Visual Basic)
© 2016 Microsoft
3 of 3 02.09.2016 17:16
Nullable Value Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ms235245(d=printer).aspx
Sometimes you work with a value type that does not have a defined value in certain circumstances. For example, a field in a
database might have to distinguish between having an assigned value that is meaningful and not having an assigned value.
Value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.
Each nullable type is constructed from the generic Nullable(Of T) structure. Consider a database that tracks work-related
activities. The following example constructs a nullable Boolean type and declares a variable of that type. You can write the
declaration in three ways:
VB
The variable ridesBusToWork can hold a value of True, a value of False, or no value at all. Its initial default value is no value
at all, which in this case could mean that the information has not yet been obtained for this person. In contrast, False could
mean that the information has been obtained and the person does not ride the bus to work.
You can declare variables and properties with nullable types, and you can declare an array with elements of a nullable type.
You can declare procedures with nullable types as parameters, and you can return a nullable type from a Function
procedure.
You cannot construct a nullable type on a reference type such as an array, a String, or a class. The underlying type must be a
value type. For more information, see Value Types and Reference Types.
Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that by
default the variable has no defined value, instead of the default value of its underlying value type. In the following
example, the variable numberOfChildren initially has no defined value, even though the default value of the Integer
type is 0.
VB
A null value is useful to indicate an undefined or unknown value. If numberOfChildren had been declared as Integer,
1 of 5 02.09.2016 17:17
Nullable Value Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ms235245(d=printer).aspx
there would be no value that could indicate that the information is not currently available.
Storing Values
You store a value in a variable or property of a nullable type in the typical way. The following example assigns a value
to the variable numberOfChildren declared in the previous example.
VB
numberOfChildren = 2
If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not
having a value assigned. You do this by setting the variable or property to Nothing, as the following example shows.
VB
numberOfChildren = Nothing
Note
Although you can assign Nothing to a variable of a nullable type, you cannot test it for Nothing by using the equal
sign. Comparison that uses the equal sign, someVar = Nothing, always evaluates to Nothing. You can test the
variable's HasValue property for False, or test by using the Is or IsNot operator.
Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a
value. If you try to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception.
The following example shows the recommended way to read the variable numberOfChildren of the previous
examples.
VB
If numberOfChildren.HasValue Then
MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
MsgBox("It is not known how many children there are.")
End If
2 of 5 02.09.2016 17:17
Nullable Value Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ms235245(d=printer).aspx
following is the truth table for And and Or. Because b1 and b2 now have three possible values, there are nine
combinations to evaluate.
b1 b2 b1 And b2 b1 Or b2
When the value of a Boolean variable or expression is Nothing, it is neither true nor false. Consider the following
example.
VB
In this example, b1 And b2 evaluates to Nothing. As a result, the Else clause is executed in each If statement, and the
3 of 5 02.09.2016 17:17
Nullable Value Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ms235245(d=printer).aspx
output is as follows:
Note
AndAlso and OrElse, which use short-circuit evaluation, must evaluate their second operands when the first evaluates
to Nothing.
Propagation
If one or both of the operands of an arithmetic, comparison, shift, or type operation is nullable, the result of the operation
is also nullable. If both operands have values that are not Nothing, the operation is performed on the underlying values
of the operands, as if neither were a nullable type. In the following example, variables compare1 and sum1 are implicitly
typed. If you rest the mouse pointer over them, you will see that the compiler infers nullable types for both of them.
VB
' Variable n is a nullable type, but both m and n have proper values.
Dim m As Integer = 3
Dim n? As Integer = 2
If one or both operands have a value of Nothing, the result will be Nothing.
VB
' Because the values of n, compare2, and sum2 are all Nothing, the
' following line displays 3 * * *
Console.WriteLine(m & " * " & n & " * " & sum2 & " * " & compare2)
4 of 5 02.09.2016 17:17
Nullable Value Types (Visual Basic) https://msdn.microsoft.com/en-us/library/ms235245(d=printer).aspx
See Also
InvalidOperationException
HasValue
Using Nullable Types (C# Programming Guide)
Data Types in Visual Basic
Value Types and Reference Types
Troubleshooting Data Types (Visual Basic)
TableAdapter Overview
If Operator (Visual Basic)
Local Type Inference (Visual Basic)
Is Operator (Visual Basic)
IsNot Operator (Visual Basic)
© 2016 Microsoft
5 of 5 02.09.2016 17:17
Value Types and Reference Types https://msdn.microsoft.com/en-us/library/t63sy5hs(d=printer).aspx
In Visual Basic, data types are implemented based on their classification. The Visual Basic data types can be classified
according to whether a variable of a particular type stores its own data or a pointer to the data. If it stores its own data it is a
value type; if it holds a pointer to data elsewhere in memory it is a reference type.
Value Types
A data type is a value type if it holds the data within its own memory allocation. Value types include the following:
Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or
ULong
Every structure is a value type, even if it contains reference type members. For this reason, value types such as Char and
Integer are implemented by .NET Framework structures.
You can declare a value type by using the reserved keyword, for example, Decimal. You can also use the New keyword to
initialize a value type. This is especially useful if the type has a constructor that takes parameters. An example of this is the
Decimal(Int32, Int32, Int32, Boolean, Byte) constructor, which builds a new Decimal value from the supplied parts.
Reference Types
A reference type contains a pointer to another memory location that holds the data. Reference types include the
following:
String
Delegates
A class is a reference type. For this reason, reference types such as Object and String are supported by .NET Framework
classes. Note that every array is a reference type, even if its members are value types.
Since every reference type represents an underlying .NET Framework class, you must use the New Operator (Visual Basic)
1 of 2 02.09.2016 17:18
Value Types and Reference Types https://msdn.microsoft.com/en-us/library/t63sy5hs(d=printer).aspx
keyword when you initialize it. The following statement initializes an array.
Namespaces
Modules
Events
You can find out whether an Object variable is acting as a reference type or a value type by passing it to the IsReference
method in the Information class of the Microsoft.VisualBasic namespace. Information.IsReference returns True if the
content of the Object variable represents a reference type.
See Also
Nullable Value Types (Visual Basic)
Type Conversions in Visual Basic
Structure Statement
Efficient Use of Data Types (Visual Basic)
Object Data Type
Data Types in Visual Basic
© 2016 Microsoft
2 of 2 02.09.2016 17:18
Type Conversions in Visual Basic https://msdn.microsoft.com/en-us/library/hcb26cc8(d=printer).aspx
The process of changing a value from one data type to another type is called conversion. Conversions are either widening or
narrowing, depending on the data capacities of the types involved. They are also implicit or explicit, depending on the syntax
in the source code.
In This Section
Widening and Narrowing Conversions (Visual Basic)
Explains conversions classified by whether the destination type can hold the data.
Related Sections
Data Types in Visual Basic
Introduces the Visual Basic data types and describes how to use them.
© 2016 Microsoft
1 of 1 02.09.2016 17:18
Widening and Narrowing Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/k1e94s7e(d=printer).aspx
An important consideration with a type conversion is whether the result of the conversion is within the range of the
destination data type.
A widening conversion changes a value to a data type that can allow for any possible value of the original data. Widening
conversions preserve the source value but can change its representation. This occurs if you convert from an integral type to
Decimal, or from Char to String.
A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. For
example, a fractional value is rounded when it is converted to an integral type, and a numeric type being converted to
Boolean is reduced to either True or False.
Widening Conversions
The following table shows the standard widening conversions.
Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double
1 of 4 02.09.2016 17:19
Widening and Narrowing Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/k1e94s7e(d=printer).aspx
Double Double
Any enumerated type (Enum) Its underlying integral type and any type to which the underlying type widens.
2 Conversions from Integer, UInteger, Long, ULong, or Decimal to Single or Double might result in loss of precision,
but never in loss of magnitude. In this sense they do not incur information loss.
3 It might seem surprising that a conversion from a derived type to one of its base types is widening. The justification is
that the derived type contains all the members of the base type, so it qualifies as an instance of the base type. In the
opposite direction, the base type does not contain any new members defined by the derived type.
Widening conversions always succeed at run time and never incur data loss. You can always perform them implicitly,
whether the Option Strict Statement sets the type checking switch to On or to Off.
Narrowing Conversions
The standard narrowing conversions include the following:
The reverse directions of the widening conversions in the preceding table (except that every type widens to itself)
Conversions in either direction between String and any numeric type, Boolean, or Date
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination
data type cannot receive the value being converted. For example, a numeric conversion can result in an overflow. The
compiler does not allow you to perform narrowing conversions implicitly unless the Option Strict Statement sets the type
checking switch to Off.
2 of 4 02.09.2016 17:19
Widening and Narrowing Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/k1e94s7e(d=printer).aspx
Note
The narrowing-conversion error is suppressed for conversions from the elements in a For Each…Next collection to the
loop control variable. For more information and examples, see the "Narrowing Conversions" section in For Each...Next
Statement (Visual Basic).
OverflowException — (integral types only) if the converted value is too large for the target type
If a class or structure defines a CType Function (Visual Basic) to serve as a conversion operator to or from that class or
structure, that CType can throw any exception it deems appropriate. In addition, that CType might call Visual Basic
functions or .NET Framework methods, which in turn could throw a variety of exceptions.
3 of 4 02.09.2016 17:19
Widening and Narrowing Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/k1e94s7e(d=printer).aspx
See Also
Data Types in Visual Basic
Type Conversions in Visual Basic
Implicit and Explicit Conversions (Visual Basic)
Conversions Between Strings and Other Types (Visual Basic)
How to: Convert an Object to Another Type in Visual Basic
Array Conversions (Visual Basic)
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
© 2016 Microsoft
4 of 4 02.09.2016 17:19
Implicit and Explicit Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/kca3w8x6(d=printer).aspx
An implicit conversion does not require any special syntax in the source code. In the following example, Visual Basic implicitly
converts the value of k to a single-precision floating-point value before assigning it to q.
Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = k
An explicit conversion uses a type conversion keyword. Visual Basic provides several such keywords, which coerce an
expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code
inline, so execution is slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value of q back to an integer before
assigning it to k.
Conversion Keywords
The following table shows the available conversion keywords.
CBool Boolean Data Type Any numeric type (including Byte, SByte, and enumerated types), String,
(Visual Basic) Object
CByte Byte Data Type Any numeric type (including SByte and enumerated types), Boolean,
(Visual Basic) String, Object
1 of 4 02.09.2016 17:20
Implicit and Explicit Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/kca3w8x6(d=printer).aspx
CDbl Double Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CDec Decimal Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CInt Integer Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CLng Long Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CSByte SByte Data Type Any numeric type (including Byte and enumerated types), Boolean,
(Visual Basic) String, Object
CShort Short Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CSng Single Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CStr String Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, Char, Char array, Date, Object
CType Type specified When converting to an elementary data type (including an array of an
following the comma elementary type), the same types as allowed for the corresponding
(,) conversion keyword
CUInt UInteger Data Type Any numeric type (including Byte, SByte, and enumerated types),
Boolean, String, Object
CULng ULong Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
CUShort UShort Data Type Any numeric type (including Byte, SByte, and enumerated types),
(Visual Basic) Boolean, String, Object
2 of 4 02.09.2016 17:20
Implicit and Explicit Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/kca3w8x6(d=printer).aspx
CType is an inline function, meaning the compiled code makes the conversion, often without generating a function call.
This improves performance.
For a comparison of CType with the other type conversion keywords, see DirectCast Operator (Visual Basic) and TryCast
Operator (Visual Basic).
Elementary Types
The following example demonstrates the use of CType.
k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)
Composite Types
You can use CType to convert values to composite data types as well as to elementary types. You can also use it to
coerce an object class to the type of one of its interfaces, as in the following example.
Array Types
CType can also convert array data types, as in the following example.
3 of 4 02.09.2016 17:20
Implicit and Explicit Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/kca3w8x6(d=printer).aspx
End If
For more information and an example, see Array Conversions (Visual Basic).
Note
Values used with a conversion keyword must be valid for the destination data type, or an error occurs. For example,
if you attempt to convert a Long to an Integer, the value of the Long must be within the valid range for the Integer
data type.
Caution
Specifying CType to convert from one class type to another fails at run time if the source type does not derive from
the destination type. Such a failure throws an InvalidCastException exception.
However, if one of the types is a structure or class you have defined, and if you have defined CType on that structure or
class, a conversion can succeed if it satisfies the requirements of your CType. See How to: Define a Conversion Operator
(Visual Basic).
Performing an explicit conversion is also known as casting an expression to a given data type or object class.
See Also
Type Conversions in Visual Basic
Conversions Between Strings and Other Types (Visual Basic)
How to: Convert an Object to Another Type in Visual Basic
Structures (Visual Basic)
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
Troubleshooting Data Types (Visual Basic)
© 2016 Microsoft
4 of 4 02.09.2016 17:20
Conversions Between Strings and Other Types (Visual Basic) https://msdn.microsoft.com/en-us/library/t6hxk86b(d=printer).aspx
You can convert a numeric, Boolean, or date/time value to a String. You can also convert in the reverse direction — from a
string value to numeric, Boolean, or Date — provided the contents of the string can be interpreted as a valid value of the
destination data type. If they cannot, a run-time error occurs.
The conversions for all these assignments, in either direction, are narrowing conversions. You should use the type conversion
keywords (CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort, and CType).
The Format and Val functions give you additional control over conversions between strings and numbers.
If you have defined a class or structure, you can define type conversion operators between String and the type of your class
or structure. For more information, see How to: Define a Conversion Operator (Visual Basic).
Note that the concatenation (&) operator can convert a number to a string implicitly, as the following example shows.
When Visual Basic converts a string to a numeric value, it uses the Regional Options settings specified in the Windows
Control Panel to interpret the thousands separator, decimal separator, and currency symbol. This means that a
conversion might succeed under one setting but not another. For example, "$14.20" is acceptable in the English (United
States) locale but not in any French locale.
1 of 2 02.09.2016 17:21
Conversions Between Strings and Other Types (Visual Basic) https://msdn.microsoft.com/en-us/library/t6hxk86b(d=printer).aspx
See Also
Type Conversions in Visual Basic
Widening and Narrowing Conversions (Visual Basic)
Implicit and Explicit Conversions (Visual Basic)
How to: Convert an Object to Another Type in Visual Basic
Array Conversions (Visual Basic)
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
Introduction to International Applications Based on the .NET Framework
© 2016 Microsoft
2 of 2 02.09.2016 17:21
How to: Convert an Object to Another Type in Visual Basic https://msdn.microsoft.com/en-us/library/x53d8wxa(d=printer).aspx
You convert an Object variable to another data type by using a conversion keyword such as CType Function (Visual Basic).
Example
The following example converts an Object variable to an Integer and a String.
If you know that the contents of an Object variable are of a particular data type, it is better to convert the variable to that
data type. If you continue to use the Object variable, you incur either boxing and unboxing (for a value type) or late binding
(for a reference type). These operations all take extra execution time and make your performance slower.
See Also
Object
Type Conversions in Visual Basic
Widening and Narrowing Conversions (Visual Basic)
Implicit and Explicit Conversions (Visual Basic)
Conversions Between Strings and Other Types (Visual Basic)
Array Conversions (Visual Basic)
Structures (Visual Basic)
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
© 2016 Microsoft
1 of 1 02.09.2016 17:21
Array Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/tbatye4h(d=printer).aspx
You can convert an array type to a different array type provided you meet the following conditions:
Equal Rank. The ranks of the two arrays must be the same, that is, they must have the same number of dimensions.
However, the lengths of the respective dimensions do not need to be the same.
Element Data Type. The data types of the elements of both arrays must be reference types. You cannot convert an
Integer array to a Long array, or even to an Object array, because at least one value type is involved. For more
information, see Value Types and Reference Types.
Convertibility. A conversion, either widening or narrowing, must be possible between the element types of the two
arrays. An example that fails this requirement is an attempted conversion between a String array and an array of a
class derived from System.Attribute. These two types have nothing in common, and no conversion of any kind exists
between them.
A conversion of one array type to another is widening or narrowing depending on whether the conversion of the respective
elements is widening or narrowing. For more information, see Widening and Narrowing Conversions (Visual Basic).
In the following example, no conversion exists between types student and String, but both derive from Object, so all
assignments are valid.
1 of 2 02.09.2016 17:22
Array Conversions (Visual Basic) https://msdn.microsoft.com/en-us/library/tbatye4h(d=printer).aspx
In the following example, students is a student array. Since no conversion exists between String and student, the
last statement fails.
See Also
Data Types in Visual Basic
Type Conversions in Visual Basic
Implicit and Explicit Conversions (Visual Basic)
Conversions Between Strings and Other Types (Visual Basic)
How to: Convert an Object to Another Type in Visual Basic
Data Type Summary (Visual Basic)
Type Conversion Functions (Visual Basic)
Arrays in Visual Basic
© 2016 Microsoft
2 of 2 02.09.2016 17:22