Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET 2.0 Beta Preview - B. Evjen.pdf
Скачиваний:
26
Добавлен:
24.05.2014
Размер:
15.33 Mб
Скачать

Chapter 15

Throughout the book I refer to the VB language as Visual Basic. With this release of the .NET Framework, the language has reverted to the name Visual Basic (minus the .NET at the end of the name). This version of the VB language is called Visual Basic 8.0, whereas the newest version of C# is 2.0.

Some new features of these two languages include those described in the following table.

New Language Feature

Visual Basic 8.0

C# 2.0

 

 

 

Generics

Yes

Yes

Iterators

No

Yes

Anonymous methods

No

Yes

Operator overloading

Yes

Yes (already available)

Partial classes

Yes

Yes

XML documentation

Yes

Yes (already available)

 

 

 

Take a look at some of these new features and how to use them in your applications.

Generics

In order to make collections a more powerful feature and also increase their efficiency and usability, generics were introduced to both Visual Basic and C#. The idea of generics is nothing new. They are similar to C++ templates. You can also find generics in other languages, such as Java. Their introduction into the .NET Framework 2.0 languages is a huge benefit for the user.

Generics enable you to make a generic collection that is still strongly typed — providing fewer chances for errors (because they occur at runtime), increasing performance, and giving you IntelliSense features when you are working with the collections.

First, look at the problems that can arise in a collection that does not use generics. Listing 15-1 shows a simple use of the Stack and Array classes.

Listing 15-1: A collection that doesn’t use generics

VB

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myStack As New Stack

myStack.Push(“St. Louis Rams”) myStack.Push(5)

Dim myArray As Array

myArray = myStack.ToArray()

For Each item As String In myArray

Label1.Text += item & “<br />”

Next

End Sub

414

Visual Basic 8.0 and C# 2.0 Language Enhancements

C#

void Page_Load(object sender, EventArgs e)

{

Stack myStack = new Stack(); myStack.Push(“St. Louis Rams”); myStack.Push(5);

Array myArray;

myArray = myStack.ToArray();

foreach (string item in myArray)

{

Label1.Text += item + “<br />”;

}

}

In this code example, you can see two distinct items in the Stack: a String with the value of St. Louis Rams and an Integer with a value of 5. The Stack itself is not the best performing item in the world simply because it is an object-based list of items — meaning that anything (as you can see in the preceding listing) can be placed in the list of items. When the For Each section is reached, however, the items are cast to a String value and displayed in a Label control. The Visual Basic example actually takes the 5, which should be an Integer, and casts it to a String and displays the St. Louis Rams and the 5 as a String in the browser. The C# example does not cast the 5 as a String, but instead throws an exception on the cast at runtime.

Generics enable you to create type-specific collections. The System.Collections.Generic namespace gives you access to generic versions of the Stack, Dictionary, SortedDictionary, List, and Queue classes. Again, you can make these collections type-specific to produce collections that perform better and that have design-time error checks and better IntelliSense features.

Listing 15-2 shows you how to create a generic version of the Stack class that includes a collection of

Strings.

Listing 15-2: A generic Stack class

VB

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myStack As New Generic.Stack(Of String)

myStack.Push(“St. Louis Rams”) myStack.Push(“Indianapolis Colts”) myStack.Push(“Minnesota Vikings”)

Dim myArray As Array myArray = myStack.ToArray()

For Each item As String In myArray

Label1.Text += item & “<br />”

Next

End Sub

(continued)

415

Chapter 15

Listing 15-2: (continued)

C#

void Page_Load(object sender, EventArgs e)

{

System.Collections.Generic.Stack<string> myStack = new System.Collections.Generic.Stack<string>();

myStack.Push(“St. Louis Rams”); myStack.Push(“Indianapolis Colts”); myStack.Push(“Minnesota Vikings”);

Array myArray;

myArray = myStack.ToArray();

foreach (string item in myArray)

{

Label1.Text += item + “<br />”;

}

}

In the example in Listing 15-2, the Stack class is explicitly cast to be a collection of type String. In Visual Basic, you do this by following the collection class with (Of String) or (Of Integer) or whatever type you want to use for your collection. In C#, you specify the collection type with the use of brackets. You cast the Stack class to type string using Stack<string>. If you want to cast it to a Stack collection of type int, you specify Stack<int>.

Because the collection of items in the Stack class is cast to a specific type immediately as the Stack class is created, the Stack class no longer casts everything to type Object and then later (in the For Each loop) to type String. This process is called boxing, and it is expensive. Because you specify the types up front, you increase performance for your collections.

Remember that when working with generic collections (as shown in the previous code example), you must import the System.Collections.Generic namespace into your ASP.NET page.

Now, change the Stack class from Listing 15-2 so that instead of working with String objects, it uses Integer objects in the collection. This change is illustrated in Listing 15-3.

Listing 15-3: A generic Stack class using Integers

VB

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myStack As New Generic.Stack(Of Integer)

myStack.Push(5)

myStack.Push(3)

myStack.Push(10)

Dim myArray As Array myArray = myStack.ToArray()

Dim x As Integer = 0

For Each item As Integer In myArray x += item

416

Visual Basic 8.0 and C# 2.0 Language Enhancements

Next

Label1.Text = x.ToString()

End Sub

C#

void Page_Load(object sender, EventArgs e)

{

System.Collections.Generic.Stack<int> myStack = new System.Collections.Generic.Stack<int>();

myStack.Push(5);

myStack.Push(3);

myStack.Push(10);

Array myArray;

myArray = myStack.ToArray();

int x = 0;

foreach (int item in myArray)

{

x += item;

}

Label1.Text = x.ToString();

}

The Stack class used in Listing 15-3 specifies that everything contained in its collection must be of type Integer. In this example, the numbers are added together and displayed in the Label control.

You can also use generics with classes, delegates, methods, and more. This is also an exciting way to apply generics. For an example, you can create a method that utilizes generics and, therefore, can work with any type thrown at it. The use of generics in methods is illustrated in Listing 15-4.

Listing 15-4: A generic method

VB

Public Function GenericReturn(Of ItemType)(ByVal item As ItemType) As ItemType Return item

End Function

C#

public ItemType GenericReturn<ItemType>(ItemType item)

{

return item;

}

This simple method returns the value that is passed to it. The value can be of any type. To construct a generic method, you must follow the method name with (Of ItemType) in Visual Basic or <ItemType> in C#. This specifies that the method is indeed a generic method.

417

Chapter 15

The single parameter passed into the method is also of ItemType and the return value is the same as the type that is established when the method is called. In Listing 15-5, note how you go about calling this generic method.

Listing 15-5: Invoking the generic method

VB

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Label1.Text = GenericReturn(Of String)(“Hello there!”)

Label2.Text = (GenericReturn(Of Integer)(5) + 5).ToString()

End Sub

C#

void Page_Load(object sender, EventArgs e)

{

Label1.Text = GenericReturn<string>(“Hello there!”); Label2.Text = (GenericReturn<int>(5) + 5).ToString();

}

This little example in Listing 15-5 shows two separate invocations of the GenericReturn method. The first instance populates the Label1 control and invokes the GenericReturn method as a String, which is quickly followed by the String value that is passed in as the item parameter. When called in this manner, the method is invoked as if it were constructed as

Public Function GenericReturn(ByVal item As String) As String

Return item

End Function

or

public string GenericReturn(string item)

{

return item;

}

The second invocation of the GenericReturn method passes in an object of type Integer, adds 5, and then uses that value to populate the Label2 control. When called in this manner, the method is invoked as if it were constructed as

Public Function GenericReturn(ByVal item As Integer) As Integer

Return item

End Function

or

public int GenericReturn(int item)

{

return item;

}

As you can see, you gain a lot of power using generics. You see generics used in both of the main .NET languages because they can be built into the underlying framework.

418