Appendix B. Variable Declarations and Data Types

This appendix provides information about variable declarations and data types.

VARIABLE DECLARATIONS

The following code shows a standard variable declaration:

[attribute_list] [accessibility] [Shared] [Shadows] [ReadOnly] _
Dim [WithEvents] name[?] [(bounds_list)] [As [New] type[?]] _
[= initialization_expression]

The following list describes the pieces of this declaration:

  • attribute_list — A comma-separated list of attributes specific to a particular task. For example, <XmlAttributeAttribute(AttributeName:="Cost")>.

  • accessibility — Public, Protected, Friend, Protected Friend, Private, or Static.

  • Shared — Means that all instances of the class or structure containing the variable share the same variable.

  • Shadows — Indicates that the variable hides a variable with the same name in a base class.

  • ReadOnly — Indicates that the program can read, but not modify, the variable's value. You can set the value in an initialization statement or in an object constructor.

  • Dim — Officially tells Visual Basic that you want to create a variable. You can omit the Dim keyword if you specify Public, Protected, Friend, Protected Friend, Private, Static, or ReadOnly.

  • WithEvents — Tells Visual Basic that the variable is of a specific object type that may raise events that you will want to catch.

  • name — Gives the name of the variable.

  • ? — Indicates this should be a nullable variable. For more information, see the section "Nullable Types" in Chapter 15, "Data Types, Variables, and Constants."

  • bounds_list — Bounds for an array.

  • New — Use New to make a new instance of an object variable. Include parameters for the class's constructor if appropriate.

  • type — The variable's data type.

  • initialization_expression — An expression that sets the initial value for the variable.

Visual Basic enables you to declare and initialize more than one variable in a single declaration statement, but that can make the code more difficult to read. To avoid possible later confusion, declare only variables of one type in a single statement.

INITIALIZATION EXPRESSIONS

Initialization expressions assign a value to a new variable. Simple expressions assign a literal value to a simple data type. The following example sets the value of a new string variable:

Dim txt As String = "Test"

The assignment expression can also initialize a variable to the result of a function or constructor, as in the following example:

Dim a_person As Person = New Person("Rod", "Stephens") " Constructor.
Dim num_tools As Integer = CountTools() " Function.

An initialization expression for an object can use the With keyword to specify values for the object's public properties as in the following example, which sets thject's FirstName and LastName properties:

Dim emp As New Employee With {.FirstName = "Rod", .LastName = "Stephens"}

To initialize a one-dimensional array, put the array's values inside curly braces separated by commas as in the following code:

Dim fibonacci() As Integer = {1, 1, 2, 3, 5, 8, 13, 21, 33, 54, 87}

To initialize higher-dimensional arrays, place lower-dimensional array values inside curly brackets and separate them with commas as in the following example, which initializes a two-dimensional array:

Dim int_values(,) As Integer = _
{ _
    {1, 2, 3}, _
    {4, 5, 6} _
}

Note that Visual Basic's automatic line continuation knows when an array initializer is open so you can omit the underscores in this statement as in the following code:

Dim int_values(,) As Integer =
{
    {1, 2, 3},
    {4, 5, 6}
}

Visual Basic's type inference system can guess the data type of an array from its initialization if Option Strict is Off. For example, in the following code, Visual Basic concludes that the array values hold Integers:

Dim values() = {1, 2, 3} ' Integer

If an array initializer holds values of more than one compatible data type, Visual Basic assumes the array holds the more general type. For example, the following array holds Doubles:

Dim values() = {1, 2, 3.4} ' Double

If an array holds values of multiple incompatible data types, Visual Basic makes the array hold Objects, as in the following example:

Dim values() = {1, 2.3, "three"} ' Object

WITH

When you create a new object variable, you can include a With clause to initialize the object's properties. The following code uses the Person class's parameterless constructor to make a new Person object. The With statement then sets values for the object's FirstName and LastName values.

Dim author As New Person() With {.FirstName = "Rod", .LastName = "Stephens"}

FROM

When you declare a collection, you can use the From keyword to initialize the collection. For example, the following code creates a collection of strings:

Dim fruits As New Collection() From {"Apple", "Banana", "Cherry"}

This works for any collection class that has an Add method.

If the collection's Add method takes more than one parameter, group parameters in brackets, as in the following example:

Dim fruits As New Dictionary(Of Integer, String)() From {
    {1, "Apple"}, {2, "Banana"}, {2, "Cherry"}}

If a class does not provide an Add method, you can create one with extension methods. The following code creates Add methods for the Stack and Queue classes:

Module CollectionExtensions
 ' Add method for the Stack class.
    <Extension()>
    Public Sub Add(ByVal the_stack As Stack, ByVal value As Object)
        the_stack.Push(value)
    End Sub

 ' Add method for the Queue class.
    <Extension()>
    Public Sub Add(ByVal the_queue As Queue, ByVal value As Object)
        the_queue.Enqueue(value)
    End Sub
End Module

USING

To make it easy to call an object's Dispose method, you can declare a variable in a Using statement. When the code reaches the corresponding End Using statement, Visual Basic automatically calls the object's Dispose method.

You can only place Using statements inside code blocks, not at the module level, so the syntax is somewhat simpler than the syntax for declaring a variable in general. The following code shows the syntax for declaring a variable in a Using statement:

Using name [(bounds_list)] [As [New] type] [= initialization_expression]
...
End Using

The parts of this statement are described in the previous section.

If it declares the variable, the Using statement must also initialize either with the As New syntax or with an initialization expression.

Note that you can also use a Using statement to make it easier to call a previously created object's Dispose method. The following code defines the thick_pen object, and then is used in a Using statement:

Dim thick_pen As New Pen(Color.Red, 10)
Using thick_pen
...
End Using

With this technique, the variable is available outside of the Using block, which may occasionally lead to confusion, so I recommend declaring variables in their Using blocks whenever possible.

ENUMERATED TYPE DECLARATIONS

The syntax for declaring an enumerated type is as follows:

[attribute_list] [accessibility] [Shadows] Enum name [As type]
    [attribute_list] value_name [= initialization_expression
    [attribute_list] value_name [= initialization_expression]
    ...
End Enum

Most of these terms (including attribute_list and accessibility) are similar to those used by variable declarations. See the section "Variable Declarations" earlier in this appendix for more information.

XML VARIABLES

To initialize XML data, declare an XElement variable and set it equal to properly formatted XML code. For example, the following code declares a variable named book_node that contains XML data representing a book:

Dim book_node As XElement = _
    <Book>
        <Title>The Bug That Was</Title>
        <Year>2010</Year>
        <Pages>376</Year>
    </Book>

OPTION EXPLICIT AND OPTION STRICT

When Option Explicit is on, you must explicitly declare all variables before using them. When Option Explicit is off, Visual Basic creates a variable the first time it is encountered if is has not yet been declared. To make your code easier to understand, and to avoid problems such as Visual Basic creating a new variable because of a typographical error, you should always turn Option Explicit on.

When Option Strict is on, Visual Basic will not implicitly perform narrowing type conversions. For example, if you set an Integer variable equal to a String value, Visual Basic will raise an error because the String might not contain an Integer value. When Option Strict is off, Visual Basic will silently attempt narrowing conversions. It tries to convert the String value into an Integer and raises an error if the String doesn't contain an integral value. To avoid confusion and potentially slow conversions, always turn Option Strict on.

OPTION INFER

When Option Infer is on, Visual Basic can infer the data type of a variable from its initialization expression. For example, Visual Basic would infer that the variable txt in the following code has data type String:

Dim message = "Hello!"

Because inferred data types do not explicitly give the variable's data type, they can make the code harder to understand. To avoid confusion, leave Option Infer off unless you really need it.

For example, LINQ (Language Integrated Query) lets a program generate results that have an anonymous type. LINQ creates an object data type to hold results but the type is not given a name for the program to use. Instead type inference allows the program to manipulate the results without ever referring to the type by name. In this case, Option Infer must be on. For more information on LINQ, see Chapter 21, "LINQ."

DATA TYPES

The following table summarizes the Visual Basic data types.

TYPE

SIZE

VALUES

Boolean

2 bytes

True or False

Byte

1 byte

0 to 255 (unsigned byte)

SByte

1 byte

−128 to 127 (signed byte)

Char

2 bytes

0 to 65,535 (unsigned character)

Short

2 bytes

−32,768 to 32,767

UShort

2 bytes

0 through 65,535 (unsigned short)

Integer

4 bytes

−2,147,483,648 to 2,147,483,647

UInteger

4 bytes

0 through 4,294,967,295 (unsigned integer)

Long

8 bytes

−9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ULong

8 bytes

0 through 18,446,744,073,709,551,615 (unsigned long)

Decimal

16 bytes

0 to +/−79,228,162,514,264,337,593,543,950,335 with no decimal point 0 to +/−7.9228162514264337593543950335 with 28 places

Single

4 bytes

−3.4028235E+38 to −1.401298E-45 (negative values) 1.401298E-45 to 3.4028235E+38 (positive values)

Double

8 bytes

−1.79769313486231570E+308 to −4.94065645841246544E-324 (negative values)

4.94065645841246544E-324 through 1.79769313486231570E+308 (positive values)

String

variable

Depending on the platform, approximately 0 to 2 billion Unicode characters

Date

8 bytes

January 1, 0001 0:0:00 to December 31, 9999 11:59:59 pm

Object

4 bytes

Points to any type of data

Structure

variable

Structure members have their own rangesa

DATA TYPE CHARACTERS

The following table lists the Visual Basic data type characters.

CHARACTER

DATA TYPE

%

Integer

&

Long

@

Decimal

!

Single

#

Double

$

String

Using data type characters alone to determine a variable's data type can be confusing, so I recommend that you use an As clause instead. For example, the following code defines two integer variables and then uses them in nested loops. The declaration of j is more explicit and easier to understand.

Dim i%
Dim j As Integer

For i = 1 To 10
    For j = 1 To 10
        Debug.WriteLine(i * 100 ? j)
    Next j
Next i

LITERAL TYPE CHARACTERS

The following table lists the Visual Basic literal type characters.

CHARACTER

DATA TYPE

S

Short

US

UShort

I

Integer

UI

UInteger

L

Long

UL

ULong

D

Decimal

F

Single (F for "floating point")

R

Double (R for "real")

c

Char (note that this is a lowercase "c")

DATA TYPE CONVERSION FUNCTIONS

The following table lists the Visual Basic data type conversion functions.

FUNCTION

CONVERTS TO

CBool

Boolean

CByte

Byte

CChar

Char

CDate

Date

CDbl

Double

CDec

Decimal

CInt

Integer

CLng

Long

CObj

Object

CSByte

SByte

CShort

Short

CSng

Single

CStr

String

CUInt

UInteger

CULng

ULong

CUShort

UShort

Remember that data types have their own parsing methods in addition to these data type conversion functions. For example, the following code converts the String variable a_string into an Integer value:

an_integer = Integer.Parse(a_string)

These methods are faster than the corresponding data type conversion function (in this case, CInt).

The Convert class also provides methods for converting from one data type to another. The following table lists the most useful Convert class functions.

FUNCTION

ToBoolean

ToByte

ToChar

ToDateTime

ToDecimal

ToDouble

ToInt16

ToInt32

ToInt64

ToSByte

ToSingle

ToString

ToUInt16

ToUInt32

ToUInt64

All of the Convert class functions provide many overloaded versions to convert different kinds of values. For example, ToInt32 has different versions that take parameters that are Boolean, Byte, String, and other data types.

The integer functions ToInt16, ToInt32, ToInt64, ToUInt16, ToUInt32, and ToUInt64 also provide an overloaded version that takes as parameters a string value and a base, which can be 2, 8, 10, or 16 to if the string is in binary, octal, decimal, or hexadecimal. For example, the following statement converts the binary value 00100100 into the integer value 36.

Dim value As Integer = Convert.ToInt32("00100100",2)

CTYPE AND DIRECTCAST

The CType and DirectCast statements also perform type conversion. CType converts data from one type to another type if the types are compatible. For example, the following code converts the string "1234" into an integer:

Dim value As Integer = CType("1234", Integer)

DirectCast converts an object reference into a reference of another type provided the reference is actually of the second type. For example, suppose the Employee class inherits from the Person class, and consider the following code:

Dim emp1 As New Employee

' Works because emp1 is an Employee and a Person.
Dim per1 As Person = DirectCast(emp1, Person)

' Works because per1 happens to point to an Employee object.
Dim emp2 As Employee = DirectCast(per1, Employee)

Dim per2 As New Person

' Fails because per2 is a Person but not an Employee.
Dim emp3 As Employee = DirectCast(per2, Employee)

The code creates an Employee object. It then uses DirectCast to convert the Employee into a Person and then to convert the new Person back into an Employee. This works because this object is both an Employee and a Person.

Next, the code creates a Person object and tries to use DirectCast to convert it into an Employee. This fails because this Person is not an Employee.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.154.16