13.4. Leveraging Cross-Language Support

Even though you can't create generics directly in J#, you do have other options available to you for creating 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()
MyBase.New()
    End Sub

    Public Sub New(ByVal initialCapacity As Int32)
        MyBase.New(initialCapacity)
    End Sub
End Class
[C# code]
using System.Collections.Generic;

namespace CSharpTypes {
    public class MyCSharpCollection<T> : List<T> {
        public MyCSharpCollection() {}

        public MyCSharpCollection(int initialCapacity) : base(initialCapacity) {}
    }
}

These classes are as simple as they come, but they serve our purpose here. Now, with these types created, ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.