Generics in Compact Framework

Wed, December 22, 2004, 05:09 AM under MobileAndEmbedded
A disclaimer up front: This is by no means a tutorial or even my original work on Generics. The subject has been discussed in depth ever since it was announced as part of Whidbey. Given that generics were not available in the Compact Framework in previous releases and I did say I would talk about them a bit, here goes some code for CF from the November CTP (tested in the emulator):

I bet 90% of the mileage on generics use will come out of using the classes in the framework and specifically the System.Collections.Generic namespace. An example is this:
' VB - consuming built-in collections
        Dim s As New System.Collections.Generic.Stack(Of Int32)
        s.Push(5)          'no boxing
        s.Push(6)
        's.Push("invalid") 'will not compile :-)
        Dim tot As Int32 = s.Pop() + s.Pop()          'no cast

// C# - consuming built-in collections
    System.Collections.Generic.Stack<int> s;
    s = new Stack<int>();
    s.Push(5); //no boxing
    s.Push(6);
    //s.Push("invalid"); //will not compile :-)
    int tot = s.Pop() + s.Pop(); //no cast

However, you can create your own generics classes and even structs:
' VB - Declare generic struct
Public Structure MyPoint(Of T)
    Dim x As T
    Dim y As T
End Structure

// C# - Declare generic struct
public struct MyPoint<T> {
    T x;
    T y;
}

...and of course consume them:
' VB - consume generic struct
        Dim mp As New MyPoint(Of Single)
        mp.x = 12.3
        mp.y = 5

// C# - Consuming own struct
    MyPoint<float> mp = new MyPoint<float>();
    mp.x = 12.3;
    mp.y = 5.2;

Even more useful, you can create generic methods and impose constraints on the types:
'VB - generic method with constraints
Public NotInheritable Class MyMath
    Private Sub New()
    End Sub
 
    Public Shared Function Min(Of T As IComparable)(ByVal a As T, ByVal b As T) As T
        If a.CompareTo(b) < 0 Then         'no casting + intellisense help
            Return a
        End If
        Return b
    End Function
End Class

// C# - generic method with constraints
public static class MyMath {
    //Min with constraints
    public static T Min<T>(T a, T b) where T : IComparable {
        if (a.CompareTo(b) < 0) {//no casting + intellisense help
            return a;
        }
        return b;
    }
}

' VB - Consume generic method
        Dim m As Int32 = MyMath.Min(6, 8)

// C# - Consume generic method
    int m = MyMath.Min(6, 8);

I have only scratched the surface here, if you want to know more about Generics I encourage you to go searching. I can recommend these articles: [1, 2]

UPDATE (7 Jan 05): Roman Batoukov has the implementation details
UPDATE (26 Jan 05): Nazim Lala has the details on reflection with generics
Comments are closed.