Types

I l @ ve RuBoard

Two kinds of types are supported in VB.NET, value types and reference types. The difference between these two kinds of types is in the way the variables of each type behave.

Value Types

Unlike reference types, variables of value types contain the actual data they represent. Value types consist of primitives (except Object and String ), enumerations, and structures.

Primitive Types

Primitive types are shorthand for CLR types found in the .NET platform. Table C.3 outlines each of the value types found in VB.NET as well as the system-provided type to which it corresponds.

Table C.3. Primitive Value Types in VB.NET
Type Name Category Description
Short System.Int16 16-bit signed integral type
Integer System.Int32 32-bit signed integral type
Long System.Int64 64-bit signed integral type
Byte System.Byte 8-bit unsigned integral type
Single System.Single Single-precision floating point type
Double System.Double Double-precision floating point type
Boolean System.Boolean Boolean type containing either True or False
Char System.Char Containing value is one Unicode character
Decimal System.Decimal New decimal type to replace less robust Currency type from previous versions of VB
Enumerations

A second kind of value type is the Enumeration, which is a user -defined type name for a group of related constants. This type is often used when a runtime decision is made from a fixed number of choices created at compile-time:

  Enum Material     Pine,     Oak,     Maple,     Mahogany End Enum 
Structures

Structures are value types that share many similarities with classes. Like classes, structure definitions can include constants, fields, methods , events, operators, constructors, destructors, and even nested type declarations. See the definition of classes for a more complete definition of these items.

When used strategically, structures can often boost performance because structure values are stored on the stack. A structure can be declared in the following manner:

 Structure Point     Public x, y, z As Integer     Public Sub New(x As Integer, y As Integer, z As Integer)         Me.x = x         Me.y = y         Me.z = z     End Sub End Structure 

We can use the structure in this way:

  Dim Graph As Point() = new Point(1000) For a = 1 to 1000     Graph(a) = new Point(a, a, a + a) Next 

By using a structure instead of a class, the calling program instantiates just one object for an array of our Point struct instead of creating 1001 new objects as it would have if we had used a class declaration.

Conversions

As mentioned before, VB.NET includes a number of primitive value types. These types also have predefined conversions between them. These conversions are either implicit or explicit.

Implicit Conversions

Implicit conversions are those that can be performed without loss of data and without careful observation. For instance, consider a conversion from Short to Integer . Because this conversion requires no loss of data, it never fails.

Explicit Conversions

Unlike implicit conversions, explicit conversions may result in loss of data and must be handled by using a cast expression:

 CInt(MyLongVariable) 

The complete list of conversion functions include: CBool , CByte , CDate , CDbl , CDec , CInt , CLng , CSng , CShort , CStr , Fix , and Int .

Reference Types

Reference types are types whose variables store only references to the actual objects they represent. Because of this, operations made on one reference type variable may affect another reference type variable if it references the same object. Reference types include arrays, classes, interfaces, delegates, and the primitive type String . The primitive type Object , the class from which all classes are ultimately derived, is neither a reference type nor a value type.

Array Types

VB.NET supports both single-dimensional and multidimensional arrays. Array types are reference types, so array declarations merely set aside space for the array. Array instances are actually created by initializing the array with array creation expressions:

  Dim arr as Integer() ' declare single-dimension array Dim arr As New Integer { 10, 20, 30}  ' initialize the array Dim arr2(,) As Integer ' declare multi-dimension array arr2 = New Integer[,] { 10, 20, 30} , { 30, 40, 50}  ' initialize the array 

Note that the preceding arrays are rectangular arrays because their shape is known. However, VB.NET also supports jagged arrays, also known as "arrays of arrays":

 Dim jagged As New Integer(5)() ' declare multi-dimension array 
Classes

Class declarations allow the programmer to create new reference types and to help employ the OOP principle of data hiding. Class declarations can include any of the following that are defined later in the appendix: fields, constants, properties, methods, events, constructors, destructors, and nested type declarations.

Member Access

Each member defined in the class declaration is accessible to one of five degrees. Table C.4 outlines the five degrees of accessibility of class members .

Table C.4. Degrees of Accessibility of Class Members
Degree Definition
Public Unlimited access
Protected Access limited to the containing class or types derived from the containing class
Friend Access limited to this program
Protected Friend Access limited to this program or types derived from the containing class
Private Access limited to the containing type
Constants

A constant is a member that represents a value computed at compile-time, which does not change. A simple class with two constants might look like this:

  Class Test     Public Const x As Integer = 1     Public Const y As Integer = x + 2 End Class 

Note that constant values can depend upon other constants as long as no circular references are created. With the appropriate access level, constants can be accessed via dot notation like any other member, as follows :

 Dim A As Integer = Test.x 
Fields

A field member is a variable associated with an object or class. Fields can be declared in the following way:

  Class Student     Public FirstName As String     Public LastName As String     Public Static ReadOnly HomeRoom As Integer     Public Sub New(First As String, Last As String, Room As Integer)         Me.FirstName = First         Me.LastName = Last         Me.HomeRoom = Room     End Sub End Class 

In this example, we have created FirstName and LastName , two instance fields, or variables for which storage is allocated with each instance of the class that is created. We have also created a third field, this time a shared field by using the Static keyword. In doing so, we have created storage for the HomeRoom field in only the class level, so all instances of the Student class will share this field. To prevent unexpected results by inadvertently overwriting data, we have used the ReadOnly keyword, which allows the field to be changed only during its declaration or a constructor of its containing class.

Properties

Like fields, properties are named members with associated types. However, properties do not designate storage locations for their associated values. Instead, they define accessors that denote the statements to execute to read or write their values. A simple class with a property declaration would resemble the following:

  Public Class PhoneNumber     Private m_PhoneNumber As String     Public Property Text As String         Get             Return m_PhoneNumber         End Get         Set             m_PhoneNumber = FormatPhone(Value)         End Set     End Property     Public Sub New(Phone As String)         m_PhoneNumber = FormatPhone(Phone)     End Sub ... End Class 

In this skeleton example of a phone number formatting class, we define both Get and S et accessors for the Text property. The Get accessor is called when the Text property is read and, conversely, the Set accessor is called when the property's value is changed. Note the implicit Value parameter of the Set accessor.

We can use this class and its properties in the following manner:

  Dim pn As New PhoneNumber("8675309") 'constructor formats TextBox1.Text = pn.Text ' Get accessor returns formatted number pn.Text = TextBox1.Text ' Set accessor, number is formatted and stored 
Methods

A method is a member that implements an action that can be performed by an object or class. Methods have a signature that consists of the number, types, and modifiers of the list of its parameters. Methods may or may not have a return type and value. For methods returning a type, the procedure is created with the Function keyword; otherwise , the Sub keyword is used. Like fields, methods may be shared methods (accessed through the class) or instance methods (which are accessed through instances of the class). We declare methods in this way:

  Public Class SportsTicker     Public Sub Start()         ' implementation goes here     End Sub     Public Shared Sub Reset()         ' implementation goes here     End Sub     Public Function GetScoreByTeam(Team As String) As GameInfo         ' implementation goes here     End Function End Class 

In this framework example, we've defined three methods. Start is an instance method with no return value, which initiates scrolling on our sports ticker. Reset is a shared method, which returns the ticker to its original state. Finally, GetScoreByTeam is an instance method, which returns a GameInfo class (defined separately) containing all the game information for the given team on the current day.

One of the more powerful features of VB.NET that developers of other languages might be familiar with is that of overloading. Methods may be overloaded, meaning they share the same name but have unique signatures. This is a useful means of providing computation on different kinds of parameters while avoiding creating unique method names for a variety of different input combinations. Consider the following example:

  Class Shape     Public Height, Width As Integer     Public Function Perimeter() As Integer         Return ((Height * 2) + (Width * 2))     End Function     Public Function Perimeter(length As Integer) As Integer         ' assume square         Return (length * 4)     End Function     Public Function Perimeter(length As Integer, width As Integer) As Integer         ' assume rectangle         Return ((length * 2) + (width * 2))     End Function     Public Function Perimeter(sides As Integer()) As Integer         ' unknown shape, calculate         Dim p as Integer = 0         For x = 0 to sides.length             p = p + sides[x]         Next         Return p     End Function End Class 

In this example, we are able to calculate the perimeter of a variety of shapes using the overloaded method Perimeter .

Events

An event is a special member that enables a class to provide notifications to the calling program. Events are declared much like fields with an added Event keyword as follows:

  Class TestClass     Public Event MouseOver As MouseOverHandler End Class 

The declaration type is always that of a delegate, in this case MouseOverHandler , which we define as follows:

 Public Delegate Sub MouseOverHandler(Sender As Object, e As System.EventArgs) 

Delegates and their other uses are discussed later in this reference.

To hook up the event handler for our event, we use the AddHandler operator from the calling program:

  Public Class TestForm     Public Sub New()         AddHandler TestClass1.MouseOver , AddressOf TestClass1_MouseOver     End Sub     Dim TestClass1  As New TestClass()     Sub TestClass1_MouseOver(Sender As Object, e As EventArgs)         ' handle event here     End Sub     Sub RemoveHandler()         ' removes the handler         RemoveHandler TestClass1.MouseOver , AddressOf TestClass1_MouseOver     End Sub End Class 
Instance Constructors

Constructors are members, which provide any initialization operations for an instance of a class. Similar in many ways to methods, constructors may be overloaded as well to provide alternate ways of instantiating a class. Constructors are created by adding a procedure named Sub New to your class. The following is an extension of our Shape class to include two constructors to allow initialization of the Height and Width fields upon instantiation.

  Class Shape     Public Height, Width As Integer     Public Sub New(h As Integer, w As Integer)         Height = h         Width = w     End Sub     Public Sub New(h As Integer)         MyBase.New()         ' assume square         Height = h         Width = h     End Sub     Public Function Perimeter() As Integer         Return ((Height * 2) + (Width * 2))     End Function     Public Function Perimeter(length As Integer) As Integer         ' assume square         Return (length * 4)     End Function End Class 

Note that the first line of a constructor must make a call to the constructor of the base class or another constructor within the class. Because we had no constructors in our class beforehand, you may have guessed that the use of constructors is optional. If no constructor is provided, the compiler automatically generates an empty constructor with no parameters.

Destructors

A destructor is a member that performs the actions required to terminate an instance of a class. Destructors have no accessibility level, take no parameters, and cannot be called explicitly. Instead, destructors are called implicitly by the system during regular garbage collection. We add destructors to a class by adding a Sub Finalize procedure.

 Sub Finalize()     'add any clean-up code here End Sub 
Shared Constructors

Shared constructors perform the required actions to initialize a class the same way as instance constructors initialize an instance of a class. However, like destructors, shared constructors have no accessibility level, take no parameters, and cannot be call explicitly. A shared constructor looks like this:

 Shared Sub New()     ' implementation code End Sub 
Inheritance

Inheritance is the mechanism that allows one type to derive from another. Classes support single inheritance and all classes ultimately derive from the object type. Consider a generic form of our Shape class once again:

  Class Shape     Public Function Perimeter(sides As Integer()) As Integer         ' unknown shape, calculate         Dim p As Integer = 0         For x = 0 to Sides.Length - 1             p = P + sides(x)         Next         Return p     End Function End Class 

Now let's derive a new type from this class:

  Class Rectangle     Inherits Shape     Public Function Area(h As Integer, w As Integer) As Integer         Return h * w     End Function End Class 

Our new class inherits the Perimeter method from Shape while adding its own Area method. However, inheritance doesn't have to be verbatim. By adding the Overridable keyword to a method or property in the base class, we may override its implementation in the derived class:

  Class Shape     Public Overridable Function Perimeter(Sides As Integer()) As Integer         ' unknown shape, calculate         Dim p As Integer = 0         For x = 0 to Sides.Length - 1             p = P + sides(x)         Next         Return p     End Function End Class 

Now let's derive a new type from this class and override the Perimeter method:

  Class Square     Inherits Shape     Public Overrides Function Perimeter(sides As Integer()) As Integer         Return p * 4     End Function     Public Function Area(h As Integer, w As Integer) As Integer         Return h * w     End Function End Class 

Often, it may be prudent to design the base class with no implementation details and stipulate that the derived class provide its own implementation. This is accomplished by marking the class as MustInherit as follows:

 MustInherit Class Shape     Public Function MustInherit Perimeter() As Integer     End Function End Class 

Our derived class is created in the same manner as in the previous example:

  Class Square     Inherits Shape     Public Overrides Function Perimeter(sides As Integer()) As Integer         Return p * 4     End Function     Public Function Area(h As Integer, w As Integer) As Integer         Return h * w     End Function End Class 
Interfaces

Interfaces are contracts that a class (or structure) implementing the interface must adhere to. Interface members may include methods, properties, and events and interfaces support multiple inheritance. They contain no implementation details because this is left to the implementing class or struct :

  Interface IValidation     Sub Validate(text As String)     End Sub End Interface Class PhoneNumber     Inherits IValidation     Sub Validate(text As String)         ' validation code goes here     End Sub End Class 
Delegates

Delegates are the VB.NET answer to function pointers in C++. However, delegates are type-safe and secure. Delegates derive from the System. Delegate type and encapsulate a callable entity, either a method on an instance class or a shared method on a class. A delegate can reference any object as long as the method's signature matches its own signature. Delegates are declared much like methods; after all, they are essentially just method signatures:

 Delegate Sub MyDelegate() 

After the delegate is declared, it must be instantiated :

  Class MyClass     Sub TestMethod()         MessageBox.Show("Calling MyClass.TestMethod")     End Sub     Shared Sub TestDelegateCall(d As MyDelegate)         d() ' calls TestMethod() anonymously     End Sub End Class 
I l @ ve RuBoard


Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net