The Array class has been expanded with many generic methods. For example, consider the following code:
int[] intArray = new int[] { 12, 34, 56, 78, 90 };
// convert each element to hex
string[] strArray = new string[intArray.Length];
for (int i = 0; i < intArray.Length; i++)
{
strArray[i] = intArray[i].ToString("X");
}
// display the result in the Console window
foreach (string s in strArray)
{
Console.WriteLine(s);
}
Using the Array.ConvertAll method and an anonymous method you can simplify the conversion loop as follows:
string[] strArray = Array.ConvertAll<int, string>(intArray, delegate(int n)
{ return n.ToString("X"); });
Surprisingly, however, you can simplify this code even further and even render it with VB 2005 (which doesn't support anonymous methods). The trick is to find a static method in the .NET Framework that takes a number and returns the argument's hex value. Strictly speaking, the .NET Framework doesn't expose a type with such a method, but you can use the Hex method of the Microsoft.VisualBasic.Conversion type:
// this code requires a reference to the Microsoft.VisualBasic.dll
string[] strArray = Array.ConvertAll<int, string>(intArray, Microsoft.VisualBasic.Conversion.Hex);
' This the VB version
Dim strArray As String() = Array.ConvertAll(Of Integer, String)(intArray, AddressOf Hex)
The Visual Basic library exposes a few other methods that you can use in this fashion, for example UCase, LCase, Trim, LTrim, RTrim, Int, Val, Asc, Chr, Len. You can find other useful methods everywhere in the .NET Framework, for example the Convert class.
Likewise, you can replace the loop that displays the results to the console window with a simpler Array.ForEach method
// C#
Array.ForEach<string>(strArray, Console.WriteLine);
' VB
Array.ForEach(Of String)(strArray, AddressOf Console.WriteLine)