Cloud Training (Online)

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
Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.