System.out.println("Instance matched");
IEnumerable<String> strEnum = (IEnumerable<String>)strCollection;
}
This example uses some of the generic types that are supplied by the
System.Collection.Generic
namespace. If you've looked at C# generics at all, you may be doing a double take as you look at this
code. The syntax in this example is actually identical to the C# generics syntax. You'll notice that J# uses
the angle brackets to enclose the list of type arguments that are supplied when constructing a generic
type. As you construct each type in this example, you'll also notice that the default, parameterless con-
structor is used, which is represented by the closed parentheses at the end of each declaration.
Constructed generic types behave like any other J# type you might use and, if you look closely at the last
few lines of this method, you'll see two more examples of some scenarios that drive this point home. The
first item that stands out here is the
if
statement that uses the
instanceof
operator to determine if the
method's incoming parameter matches a specific generic type. And, in the next block of code, you'll also
see where a cast is used to cast an instance of a collection to an
IEnumerable<String>
. Both of these
examples should make it clear that J# generic types can be used in the same context as any other non-
generic J# type.
It's also worth noting that any J# primitive or reference type can be used as a type argument when con-
structing a generic type. And, unlike Java generics, the value types you supply here will not need to be
boxed and unboxed. Because generics are represented in IL, any generic type constructed in J# will bene-
fit from all the same efficiencies that are associated with other languages in the .NET platform.
Leveraging Cross-Language Suppor t
Even though you can't create generics directly in J#, you do have other options available to you for creat-
ing your own generic types. The beauty of the CLR is its ability to easily support the mix-and-match of
languages within a single solution. So, if you are determined to stick with J# for much of your coding
but want to create the occasional custom generic type, your best option is to hop on over to one of the
other .NET languages.
Here's a quick example that demonstrates this concept in action. It starts by creating some very simple
generic types that are just subclasses of existing generic types. And, to further demonstrate the cross-
language nature of generics and to show I don't play favorites, this example includes classes that are
implemented in both C# and Visual Basic. The code for these classes is as follows:
[VB code]
Imports System.Collections.Generic
Public Class MyVBDictionary(Of K, V)
Inherits Dictionary(Of K, V)
End Class
Public Class MyVBCollection(Of T)
Inherits List(Of T)
Public Sub New()
281
Using Generics with J#
16_559885 ch13.qxd 9/8/05 11:06 PM Page 281