Consuming Generic Types

To instantiate and consume generic types, you pass to the constructor the type you want to be handled. For example, the following code creates a new instance of the CustomType class enabling it to handle only integers or types that are converted to Integer via a widening conversion:

image

Basically you pass the desired type to the constructor after the Of keyword. When invoking the Add method, you can notice how IntelliSense tells you that the method can receive only Integer. If you pass a different type, you get an error message. But this does not work only with .NET common types. You can use this technique with custom types, too. For example, you can create a generic collection of Person objects (supposing you have defined a Person class in your code) as follows:

image

Hopefully Generics’ purpose is now clearer. Their purpose is to provide reusable infrastructures for different types avoiding mixed groups of objects in favor of strongly typed objects.

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

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