Generics in VB.NET

Generics in VB.NET

By Sonu Kapoor


Abstract
Introduction

What are Generics?

Why should I use Generics?

 

 

Abstract:

 

Generics are very useful if you know what they are and how to use them. In this article we will dive into the world of generics. We will show you what generics are and what they are used for. We will show you situations and practical examples where the usage of generics makes sense. Once you have completely read the article, you will understand what the term generic stands for and how it can be used in your own projects.

 

Introduction:

 

C++ was one of the first languages, which used some types of generics, however they were called “templates”. C# uses a similar syntax as the C++ templates, however in C# they are much easier to use. Generics are first available in Whidbey. Earlier versions of the CLR don’t support it. <> is used in C# to define a generic. However in VB.NET we use the keyword “Of”. In this article we will only discuss the VB.NET syntax.

 

What are Generics?

 

The term “generic” means not to be bound to any specific type regardless of whether we are referring it to any programming language or not! Just think of a “glass”, which can be filled with the following types: water, juice, soda etc. As you can see it is not bound to one type. It can be filled with any type. In the same way we can refer it to VB.NET. We could create a class called “Glass” which could store any of these types depended on the users choice.

Generics in one sentence:
Generics can be used to store collections, which are not bound to any data type.

 

Why should I use Generics?

 

Just imagine that you are working in a class where you would need to store different data types in a collection. Of course you could use an array, but don’t forget that you will need to create different arrays for different data types, which will just bloat your code. Furthermore your code will be unnecessary longer than needed. In that case we can use generics. We could use one generic class that could handle all of data types, without requiring writing the code again and again. This will save our time, resources, and increase the performance, because the user would not need to cast the data types. In summary we can say that generics are used for the following reasons:

 

  • Performance
  • Type Safe
  • Code Reuse

 

Performance:

 

How can generics help the developer to get a better performance? This is simple. The data-types are checked in the compile-timer rather than in run-time. Simply this change will improve the performance. No type casting necessary at run-time. However you should know that performance and speed are not the main aspects to use generics, but in maintainability and cleaner code.

 

Type Safe:

 

This means that whenever you add an object to the collection it is checked at compile time. That means that the data type should be safe and if you pass a wrong data-type to the collection, it will throw an error during the compile time and not in the run time. This way you can make sure to handle all errors so that they don’t appear at run time, when the client is using the application.

 

Code Reuse:

 

If you want to store different data types in a (non-generic) collection, than you won’t have any other option than declaring different collections for that. For example: You will need to declare a collection for integers, another for strings and another for double data types. These will unnecessary bloat your code. When using generics you just need to set the data type as a parameter and viola you can use it with whatever type you like.

 

Simple Example

 

We have read a lot by now. It’s time to see some code. To demonstrate how simple it is to use we have chosen a simple example. Lets see how it looks like:

Our Gen Class:

Public Class Gen(Of T)

    Dim dataType As T

    Public Property Val() As T

        Get

            Return dataType

        End Get

        Set(ByVal value As T)

            dataType = value

        End Set

    End Property

End Class

 

Our Main:

 

Sub Main()

        ' This one accepts strings

        Dim mystring As New Gen(Of String)

        mystring.Val = "hello world"

        System.Console.WriteLine(mystring.Val)

 

        ' Change the declaration so that it accepts now an integer

        Dim myInt As New Gen(Of Integer)

        myInt.Val = 5

        System.Console.WriteLine(myInt.Val)

 

        Console.WriteLine("Press Enter to finish ... ")

        Console.Read()

End Sub

 

Our Output:

 

hello world
5

 

How it works:

As you can see above we have only two main parts. The first is the class “Gen” and the second is the main function. The “Gen” class is generic. As already described in the introduction we need the “Of” keyword to declare it as generic. In C# and C++ we can use <> to create generic classes.

 

The “T” next right to the “Of” represents our data-type which we will pass when we create a new instance of that class. The rest of the code should be familiar to you.

 

The interesting part is going on in the main function where we create two instances of the “Gen” class. In the first instance we are using a String. This will allow passing string values to the class variables.

 

        Dim mystring As New Gen(Of String)

        mystring.Val = "hello world"

        System.Console.WriteLine(mystring.Val)

 

In the second instance we are using an Integer. Here we can use integer values to pass to the class variables.

 

        Dim myInt As New Gen(Of Integer)

        myInt.Val = 5

        System.Console.WriteLine(myInt.Val)

 

As you can see this was our first simple generic example. To get the same result without using generic, will cost you two classes. Your code will just bloat for nothing. The first one would need a string and the second one could use an integer, but what if you decide to create a third data-type, lets say a double? Well then you will need to create a third class, which will again make your code longer than it already is. While using generics you only need one class for any data-type.

Filed under:

Comments

# JJ said:

This is a very good piece of tutorial. I have seen lot other tutorials on Generics, but this one is better than all that, since it makes the tutorial clear, simple and to get the concept without much confusion. And surely a better place to start learning.

Thursday, July 26, 2007 5:28 AM
# Mohan said:

Here the given sample is simple and clear to start working with generics without any confusion.

It's better place to start with Generics

Friday, August 03, 2007 5:23 AM
# amu said:

Yes it does work with  windows application but i am using A.S.P.net.I am looking for a Generic class in a three tier architecture using oracle as a database.

I am desperate would you please help me if you can.

respond to www.webmail.co.za

Thursday, August 16, 2007 4:22 AM
# soumya said:

i am using A.S.P.net.can you please help me about how to use it in asp.

Friday, October 19, 2007 5:53 AM
# Brian said:

Doesn't creating an overloaded function do the same thing or am i totally missing the point?

Brian

Thursday, November 08, 2007 3:32 PM
# Mohan said:

This article gives you a clear picture to start of with the generics.

Regards,

Mohan

Wednesday, November 28, 2007 9:58 AM
# ngonidan said:

I shall say no more. You simply hammered right to the marrow!!!

Monday, December 03, 2007 1:09 PM
# Qutub said:

Good one appreciated.

Wednesday, January 30, 2008 5:52 AM
# prasanna said:

The way in which u have explained is realy supereb

Wednesday, February 20, 2008 5:39 AM
# d razen said:

one word: cool ! :-)

Thursday, February 28, 2008 12:32 PM
# PS said:

this is a very nice tutorial to uderstand concept of generics.looking forward to have such tutorials on other features of .net which are new to developers

Wednesday, March 12, 2008 3:05 AM
# bjames said:

Very nice tutorial.  I'm no longer confused by generics.

Good work.

Thursday, April 03, 2008 4:32 AM
# Paddy said:

it was very comprehensive. it gave me a very clear concept of the same. Very commendable job.

Friday, April 18, 2008 8:47 AM
# raja said:

Thanks a lot Sonu, All r copying same example of Stack so on but none of them created zeal to see at the code even.

Sunday, August 24, 2008 12:38 AM
# badari said:

This Article good introductions about generics

Thanks for your Information

Sunday, September 21, 2008 11:16 PM
# PrasadaRao Ryali said:

Very Cleare artical .ThankS.

Monday, October 06, 2008 3:25 AM
# Yoga said:

very clear and brief article to get started....

Thanks

Thursday, November 20, 2008 1:47 AM
# Aka said:

not a good article

Friday, December 26, 2008 12:59 AM
# Farhan Jamal said:

I think we can do the same things by declaring variable as  object type in a class. Secondly i write following code using generics but this will not result the compile time error but as per article it should show compile time error (Type Safe -Generics).

Dim myList as New List(Of Integer)

myList.Add(1)

myList.Add("Some Text") ' It is run-time not a compile time

Tuesday, May 26, 2009 8:17 PM
# ErickTreetops said:

I'd like to see something just as good on generic methods who's syntax i find very confusing.

Tuesday, October 06, 2009 9:42 PM
# abrly said:

Excellent Article, simple but powerful, Keep Up Good Work

Wednesday, October 21, 2009 7:32 AM
# nikhil said:

i like ur way to explain abt generics. it's

really benifitial keep it up.

Friday, October 30, 2009 8:47 AM
# Francis said:

Brilliantly simple and to the point.

Friday, December 25, 2009 1:50 PM
# Nice said:

Thanks for introducing me to the 'Of' keyword

Thursday, April 01, 2010 10:54 AM
# internet user said:

your example and explain way is excellent. good keep it up like wise you can give some more concept ... it will keep people in ind easily...

Friday, July 09, 2010 1:54 PM
# Sandeep Tiwari said:

Thanks for such a nice article.....I have been strying to master the concept since long.....and this article works like wonder to me. Thanks lot!!!!

Sunday, July 11, 2010 8:15 AM
# Narinder said:

Nice explanation. I did not understand from 3 books but got clear picture of it. , Thanks , Better if some example is added , how to add generics in sorted list or collection.

Tuesday, September 14, 2010 10:52 PM
# Soprano SaXophone said:

ohh…wonderful publish but genuinely?/? :P

--------------------------------------------

my website is  

http://flying-v-guitar.com

Also welcome you!

Tuesday, November 23, 2010 3:50 AM
# ipad accessories stylus said:

To be both a speaker of words and a doer of deeds.

-----------------------------------

Monday, December 20, 2010 12:43 AM
# hd video camera reviews said:

Hi. I learn a few of your respective other articles and needed to know if you would be interested in exchanging blogroll links?

--------------------------------------------------------------------    

Harvard Integrated Life Sciences

Monday, January 17, 2011 7:07 PM
# webcams reviews said:

The catchy blog with the interesting posts. You give the good details that numerous men and women do not know before. most of your contents are make me have extra understanding. it is extremely diverse. I was impressed together with your web site. Never be bored to visit your website again. Have the nice working day.Hold loved your blogging.

--------------------------------------------------------------------    

Middle Eastern Studies

Sunday, March 13, 2011 8:45 AM
# anu said:

Excellent article...very informative...

Tuesday, March 15, 2011 1:01 PM
# writing iphone apps said:

"As a Newbie, I'm constantly seeking on the web for posts which will support me. Say thanks to you"

--------------------------------------------------------------------        

Stem Cell and Regenerative Biology

Wednesday, April 27, 2011 8:16 PM
# The Master of VB said:

Today is 9/22/2011 and I start to read about the Generic... I am a very late runner. Even though this article was written in 2004 but very informative. I read many of others about GeneROCK but they just twisted AND BLOCK my brain.

AAA++++.....

Thank  you

Thursday, September 22, 2011 11:53 AM

Leave a Comment

(required) 
(required) 
(optional)
(required)