Introducing generics (i) to Visual Basic programmers

Source: Internet
Author: User
Tags arrays hash new features sort visual studio
visual| Program | Programmer This document is Sean Campbell, Scott Swigart, Kris Horrocks, Derek Hatchard, and Peter Bernhardt. to Microsoft Visual Basic Programmer Introduction Whidbey "a chapter in the book, the copyright belongs to the original author and publishing house." Reprint please indicate this statement.

This article uses popular terminology and a large number of examples to explain to visual Basic programmers the new features that will be added to the next version of Visual Basic.NET-generics. This article can help the vast majority of VB users understand generics, so that in the future to apply generics to their applications.

Application: Generics

This application shows the newly added generics functionality in Visual Basic.NET.

New concept

Before you begin implementing generics, it is necessary to take a moment to analyze why you want to add this functionality to the Visual Basic.NET. Generics technology stems from the need to deal with the various possible types of objects in a generic way without having to care about their specific types. For example, in Visual Basic 6.0, you can store objects of any type with a collection class.

Collection of Visual Basic 6.0

Visual Basic 6.0 does allow you to store everything in a collection. However, the collection class has several limitations. We use an example to illustrate how to store this employee class in the collection:

' Visual Basic 6.0 code: class module Employee

Public SSN as String

Public FirstName as String

Public LastName as String

Public Salary as Currency

The way in which this class is stored in the collection appears very straightforward.

' Visual Basic 6.0 code

Dim employees as New Collection



Dim EMP as Employee

Set emp = New Employee

Emp. SSN = "111-11-1111"

Emp. FirstName = "Scott"

Emp. LastName = "Swigart"

Emp. Salary = 50000



Employees. ADD EMP, EMP. Ssn

This code first creates a collection instance of employees. The employee class then creates an instance and sets some data. Finally, the employee object is added to the collection, specifying the EMP. The SSN property as a keyword. The following code shows how to remove an instance of this Employee object from collection:

' Visual Basic 6.0 code

Dim EMP2 as Employee

Set EMP2 = Employees ("111-11-1111")

Now let's look at the limitations of this collection of Visual Basic 6.0. First, your intention is to have employees this collection to store only the employee type objects. But there is no mechanism to prevent a different type of object from being put into this employees set, and nothing can tell you what type of data is taken from this collection. The following code can compile correctly:

Dim S as String

s = Employees ("111-11-1111")

Although developers can be very clear that this does not work correctly, there is no way for the compiler to find out about this problem. This will cause a run-time error. The use of collections also limits the play of IntelliSense technologies. Look at the following code:

Employees ("111-11-1111"). LastName = "Someoneelse"

This means you can edit the items in the collection directly. However, the IDE's IntelliSense does not help you choose the LastName attribute. Once again, the collection in the previous visual Basic can hold anything.

The two biggest limitations of using a collection are performance and flexibility losses. Collections are easy to use, but performance is very poor when used as a dynamic array. The design of the set makes it more like a dictionary, so when you need a data structure like a stack or queue, it is not a good choice.

A collection in a frame

. NET Framework 1.0/1.1 solves part of the problem by increasing the kind of collection. After the new System.Collections namespace is introduced, you can create more types of collections, such as array tables, bit arrays, hash tables, queues, sort lists, and stacks. The following table lists the usage of these types:

Collection name
Use

ArrayList
Array tables can create dynamically enlarged arrays.

BitArray
The bit array is optimized for storing an array of Boolean values (True/false).

HashTable
The hash table is very similar to the collection class in Visual Basic 6.0. It allows you to find the corresponding value by keyword. However, the keyword and value are any type.

SortedList
A sort table is very similar to a Hashtable, except that its keywords are always sorted. This means that when you use a for ... Each syntax iterates through the collection, and the resulting items are always sorted.

Queue
A queue is a set of objects that allow a stored object to be advanced first.

Stack
A stack is a collection that allows a stored object to be LIFO first.



The. Net framework 1.0/1.1 has resolved the flexibility limitations of the collections in Visual Basic 6.0, but these collections are still weakly typed, so you can still store anything in a ArrayList, although in a given application, Only storing a unique type makes sense.

What you really want is to specify that each keyword must be string and that each value is an employee type. In the. NET Framework 1.0 and 1.1, you only have to create your own class, of course this method is somewhat cumbersome. If you use a new. NET Framework 1.2, this problem can be solved with very little code, the method is to use generics.

Deep code

Generics provide rigorous type checking, better IntelliSense capabilities, and better performance, as described in the previous section. In other words, they go beyond the benefits that all previous collection classes can offer.

Feel the generic type

Next you will see that when you create an instance of a generic collection, you need to provide some information so that the collection class can be strongly typed. This has many advantages, including more checks during the compile phase to make sure that more secure and reliable code is created, better IntelliSense, and better performance. It is necessary to mention. NET Framework 1.2 is a new addition to the generic collection on the basis of previous versions. NET Framework 1.2 does not force you to use generics.

If you want to use a generic type, you first need to include the System.Collections.Generic namespace. This allows access to dictionary, List, Queue, SortedDictionary, and stack classes with generic functionality. The code in the following Btnconsumegenerics_click event provides an example of using a generic dictionary:

' Visual Basic. NET 8.0 Code

Private Sub Btnconsumegenerics_click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Btnconsumegeneri Cs. Click

Dim employees as New Dictionary (of String, Employee)

Dim EMP as Employee

EMP = New Employee

Emp. SSN = "111-11-1111"

Emp. FirstName = "Scott"

Emp. LastName = "Swigart"

Emp. Salary = 50000



Employees. ADD (EMP. SSN, EMP)



Dim EMP2 as Employee

EMP2 = employees. Item ("111-11-1111")



Dim S as String

' s = employees. Item ("111-11-1111") ' This was now a syntax error



Employees. Item ("111-11-1111"). LastName = "Someoneelse"

End Sub

If you look at the code in depth, you'll notice something quite interesting in the generics technology. First, the generic type is materialized in such a way:

Dim employees as New Dictionary (of String, Employee)

This can be translated as "create a dictionary, its keyword is string type, value is employee type". Any attempt to store an object that is not an employee type will result in a compilation error. It is necessary to reiterate that if generics are used, you will get a compile error instead of a run-time error if you use the wrong type again. In fact, the following code is not compiled unless it is commented out, just as the compiler knows that dictionary is dedicated to storing employee objects, not string:

' s = employees. Item ("111-11-1111") ' This was now a syntax error

Further, you will now have full awareness support. If you type "employees." Item ("111-11-1111")., the members of the employee type will automatically pop up, which means that Visual Studio knows that dictionary is now a collection of specially stored employee classes.

(After the introduction of generics (ii) to Visual Basic programmers)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.