Hi
I am fairly proficient in vb6 and vb.net but I am baffled by generics. What
are generics about and can I make use of them in my winform vb.net database
applications?
Many Thanks
Regards
Generics are really a way to make reusable algorithms and containers
that are type agnostic. For example, one of the commonly used
container classes in the framework is System.Collections.ArrayList.
ArrayList, was great - it gives you dynamic resizing and you can stick
anything you want into it - at a price. That price is performance.
It's not so bad with reference types, though you still have over head
of a casting every time you wanted to access a value in your
arraylist. The performance gets even worse with value types, because
of the boxing operations that have to occur. And if you think about
it - probably 99% of the time, your not mixing objects in the
ArrayList - by that I mean you almost always make it a list of
integers, doubles, strings, or some other object. Wouldn't be nice to
be able to just say:
Dim firstName As String = MyList(2).FirstName
Instead of something like:
Dim thePerson As Person = DirectCast(MyList(2))
Dim firstName as String = thePerson.FirstName
With generics, these problems are overcome. If you look in
System.Collections.Generic, you will see the List class. List is
equivalent to ArrayList - it is a dyanmic container. The big
difference (besides, some very convienient new methods - find,
findall, etc.) is that List is generic. So? Well it means when you
declare a list:
Dim MyList As New List(Of Person)
You get a typesafe list, that can only hold people. Not only that,
because of this the compiler knows it's a list of people. So you can
just access it like:
Dim firstName As String = MyList(2).FirstName
No cast. No fuss
As for performance, I haven't tested it myself,
but I've seen others say that they get as much as a 30% increase in
performance with a list of value types and 10% increase with reference
types. Not bad.
Containers classes aren't the only use - you can also create generic
methods and algoriths that work on multiple types more easily. You
can actually add constraints to your generic methods and containers so
that you know that all objects in that container must implement a
specific interface or inherit from a specific type.
There is a lot to generics - and yes, sure you could make use of
generics in a windows db application... I suggest that you open the
documentation and read about them. They are a little confusing at
first glance, but once you start using them - I'm pretty confident
that you will come to really appriciate the power and flexability they
add to your programming toolset.