The longer I work with generics, the more I like them, and I continue to discover new ways to simplify my code by using them. More specifically, I like the ability to write type-safe code that is also more concise, efficient, and (above all) readable, because I don't have to use tons of CType and DirectCast operators. Today I gathered the generic methods I use more frequently in the following module. They are tiny and simple, yet they save me a lot of time and code.
Module
End
Most methods are self-explanatory. One of the most useful ones is NewArray, which lets you create an array and pass it on-the-fly to a method. Let's say the the DoSomething method takes an array of Integers. These are the options you have in VB2005:
I often use the second syntax, but I noticed that relatively few developers know it. My code is much more readable with the NewArray method
The NewArray method proves to be quite useful also to build For loops whose index can take any sequence of values:
' Test whether "number" is a prime number in the range 1-1000 For Each n As Integer In NewArray(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31) If (number Mod n) = 0 Then Console.Write("{0} is not prime", number): Exit For Next
Remember Me
Powered by: newtelligence dasBlog 1.8.5223.1