Geeks With Blogs
A Technical Debtor Toward continuous improvement

I had a case today where I needed -- well, wanted -- to implement a generic class that was a little... unusual.

Essentially, I'm working on a queuing mechanism based on Joe Duffy's BlockingBoundedQueue(Of T). Mind you, unlike Joe's sample, mine is written in VB.NET. ;)

Taking it a bit further, I created a wrapper that specifies the number of producers and consumers of queued objects, as well as the queue capacity. Since I'm going to be turning this over to a bunch of developers to play with, I also wanted to be able to specify more tightly what types can be used for producers and consumers. This type specification also lets me raise events for diagnostics.

Now, this all sounds kind of easy, doesn't it? Well, it is... until you go looking for a good example of the syntax for generics with multiple constraints. I usually get good results from Google, and this took me far too long to find, so I thought I'd post it here.

The key is wrapping the multiple constraints for a single generic argument in the dreaded curly braces. A simple example is:

Public Class myClass(Of T As {New, myBaseClass})

A more complicated example could look something like this:

Public Class DataQueue(Of P As {New, Producer(Of T)}, C As {New, Consumer(Of T)}, T)
Posted on Tuesday, November 18, 2008 5:05 PM Tips and Tricks , VB , DevCenter | Back to top

Comments on this post: VB.NET Generics with Multiple Constraints

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Jeff Certain | Powered by: