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:
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:
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.
18.188.227.92