Generics in VB.Net

Taking a lead (again) from Java generic types for beginners, I decided to experiment with generic types in VB.Net. The ICT Cool blog covers the idea behind generics and the MSDN documentation on generic types in VB.Net gives more details on the topic, so I won’t repeat what has been explained elsewhere.

My code shows how generics can make code more robust by enforcing compile time type checking. The type safety of the various objects can be checked in Visual Studio by hovering the mouse over any of the variables in the code. This brings up a pop up that says the type of the object. Many of the lines of the main sub have been commented out because the project would not build otherwise. Try uncommenting them to see the errors that the IDE finds.

The code also shows that generic types allow coders to build and use type safe, polymorphic collections. Put simply, we can create a list (for example) that will only allow us to add an object of any type, so long as it implements an interface given at the time of construction.

GenericsInLists

2 Responses to “Generics in VB.Net”

  1. Brian Pizzey says:

    Robert,

    Would it be possible for you to post important snippets of code to your blog articles – displayed inline – rather than require readers to download a zip file and wade through the code? I’m very interested to see what you are working on, but I don’t use .NET and I’m not on Windows. It would nonetheless be interesting to see the similarities between .NET and Java code.

    My blog uses the SyntaxHighlighter Evolved WordPress plugin if that’s any use to you.

  2. Robert Impey says:

    That sounds like a great idea. I’ll take a look at the plug-in that you mention. Another approach that I’ve been considering is to put all my little code experiments on github, . A mixture of both is probably about right.

    I’ve tried the code from this post on a Mac with MonoDevelop. Interestingly, the code behaved slightly differently on mono and the compiler failed to spot an illegal operation.

Leave a Reply