Using Array.ConvertAll to Convert an array of one type to another in C#

Thanks to one of My friend (Anil pai) , who asked me a question on how to convert a string array to an float/Double Array which made me to explore the  possibilities in .NET and this is when i came across Array.ConvertAll

The usual way of doing this is to parse and convert each values one by one like this

string[] sArray = new string[]{"1","3"};
decimal[] dArray = new decimal[2];
for (int i=0; i < sArray.Length; i++)
{
    dArray[i] = Convert.ToDecimal(sArray[i]);
}

Now , Array.ConvertAll makes the things easier for us .

You can use Array.ConvertAll method to convert an array of one type to an array of another.

This method is found in the namespace – System and the assembly mscorlib.dll .

The first parameter is the input array and the second parameter is the Converter which represents a delegate method that converts an object from one type to another type. .

public static void Main()
{
string[] sArray = new string[]{"1","3"};
decimal[] dArray = Array.ConvertAll<string, double>sArray,Convert.ToDouble);
}

This will help simplify the code especially when there are many different conversions in the program .

This method is supported in the following .NET framework

  • .NET 4.0
  • .NET 3.5
  • .NET 3.0
  • .NET 2.0

0 thoughts on “Using Array.ConvertAll to Convert an array of one type to another in C#

  1. Pingback: Using Array.ConvertAll to Convert an array of one type to another in C# | ProgramInDotnet

Leave a Reply

Your email address will not be published. Required fields are marked *