Array.ConvertAll(TInput[], Converter<TInput, TOutput>) Method is used to convert an array of one type to an array of another type.
Syntax:
public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array,
Converter<TInput,TOutput> converter);
Here, TInput and TOutput is the source array and target array respectively.
Parameters:
array: It is the one-dimensional, zero-based Array to convert to a target type.
converter: It is a Converter that converts each element from one type to another type.
Return Value: This method returns an array of the target type containing the converted elements from the source array.
Exception: This method throws ArgumentNullException if the array is null or converter is null.
Below programs illustrate the use of Array.ConvertAll(TInput[], Converter<TInput, TOutput>) Method
Example 1:
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
try {
int [] myArr = {10, 20, 30, 40};
Console.WriteLine( "Initial Array:" );
PrintIndexAndValues(myArr);
String[] conarr = Array.ConvertAll(myArr,
new Converter< int , String>(intToString));
Console.WriteLine( "Converted Array:" );
PrintIndexAndValues(conarr);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
public static void PrintIndexAndValues( int [] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
public static String intToString( int pf)
{
return pf.ToString();
}
}
|
Output:
Initial Array:
10
20
30
40
Converted Array:
10
20
30
40
Example 2:
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
try {
int [] myArr = null ;
String[] conarr = Array.ConvertAll(myArr,
new Converter< int , String>(intToString));
PrintIndexAndValues(conarr);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
public static String intToString( int pf)
{
return pf.ToString();
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!