Creating and Consuming Generics

Creating a generic type is accomplished by providing a parameterized type definition. The following is an example:

image

The Of keyword is followed by the type that the new object can handle. T is the type parameter and represents the .NET type that you want to be held by your generic type. The type parameter’s name is left to your own choosing, but you often find T as a common name in the .NET Framework base class library. At this point you must write code to manipulate the T type in a way that will be convenient for possibly every .NET type. Now imagine you want to build a custom collection that you want to reuse with any .NET type. Listing 14.1 shows how to accomplish this.

Listing 14.1 Building a Custom Generic Type

image

Tip

You notice that the code in Listing 14.1 uses arrays to store objects. Arrays do not support removing objects or, at least, this cannot be accomplished easily, and this is the reason why you only find an Add method. By the way, in this particular case you do not need to focus on how to add and remove items (Chapter 16 is about this) whereas you instead need to understand how to handle the generic type parameter.

The code shows how simple it is to manage the type parameter. It can represent any .NET type but, as in the previous example, an array can be of that type and store objects of that type. Because arrays cannot be empty, the constructor receives the upper bound that is then used by ReDim. The Add method equally receives an argument of type T whose value is pushed into the array. This introduces another important concept: generic methods, that is, where methods can accept generic parameters (named type argument). Notice how a Count property returns the number of items in the array. In this particular scenario, auto-implemented properties cannot be used because a read-only property needs a Get block. Finally, the Item property enables retrieving the specified object in the array at the given index. The new class therefore can handle different types with the same infrastructure.

What Can be Generics?

You can define as generic the following types: classes, interfaces, delegates, structures, and methods.

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

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