Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Copy the Stack to an Array
Next article icon

C# | Converting an array of one type to an array of another type

Last Updated : 01 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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:




// C# program to demonstrate
// Array.ConvertAll() Method
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing
            // new the Array of int
            int[] myArr = {10, 20, 30, 40};
  
            // Display the values of the myArr.
            Console.WriteLine("Initial Array:");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(myArr);
  
            // converting int myArr to String conarr
            String[] conarr = Array.ConvertAll(myArr, 
              new Converter<int, String>(intToString));
  
            // Display the values of the myArr.
            Console.WriteLine("Converted Array:");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(conarr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // intToString
    public static String intToString(int pf)
    {
        return pf.ToString();
    }
}
 
 
Output:
  Initial Array:  10  20  30  40    Converted Array:  10  20  30  40  

Example 2:




// C# program to demonstrate
// Array.ConvertAll() Method
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing new 
            // the Array of int with null value
            int[] myArr = null;
  
            // converting int myArr to String conarr
            String[] conarr = Array.ConvertAll(myArr, 
             new Converter<int, String>(intToString));
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(conarr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // intToString
    public static String intToString(int pf)
    {
        return pf.ToString();
    }
}
 
 
Output:
  Exception Thrown: System.ArgumentNullException  

Reference:

  • https://docs.microsoft.com/en-us/dotnet/api/system.array.convertall?view=netframework-4.7.2


Next Article
C# | Copy the Stack to an Array

R

RohitPrasad3
Improve
Article Tags :
  • C#
  • CSharp-Arrays
  • CSharp-method

Similar Reads

  • C# | How to convert an ArrayList to Array
    In C#, an array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float etc. and the elements are stored in a contiguous location.ArrayList represen
    4 min read
  • C# | Copying the elements of ArrayList to a new array
    ArrayList.ToArray Method is used to copy the elements of the ArrayList to a new array. This method contains two methods in its overload list as follows: ToArray()ToArray(Type)ToArray() This method is used to copy the elements of the ArrayList to a new Object array. The elements are copied using Arra
    2 min read
  • C# | How to copy the entire ArrayList to a one-dimensional Array
    ArrayList.CopyTo Method is used to copy the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array. Syntax: public virtual void CopyTo (Array array); Here, array is the one-dimensional Array which is the destination of the elements copied from ArrayList
    3 min read
  • C# | Copy the Stack to an Array
    Stack<T>.CopyTo(T[], Int32) Method is used to copy the Stack<T> to an existing 1-D Array which starts from the specified array index. Properties: The capacity of a Stack<T>is the number of elements the Stack<T> can hold. As elements are added to a Stack<T> , the capacit
    2 min read
  • C# | Buffer.BlockCopy(Array, Int32, Array, Int32, Int32) Method
    This method is used to copy a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset.Syntax: public static void BlockCopy (Array src, int srcOffset, Array dst, int dstOffset, int count); Parameters: src: It is the source b
    9 min read
  • C# | Convert Stack to array
    Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.ToArray Method is used to copy a Stack<T
    2 min read
  • C# | Array.ConstrainedCopy() Method
    This method is used to copy a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely. Syntax: public static void ConstrainedCop
    9 min read
  • C# | Implicitly Typed Arrays
    Implicitly typed arrays are those arrays in which the type of the array is deduced from the element specified in the array initializer. The implicitly typed arrays are similar to implicitly typed variable. In general, implicitly typed arrays are used in the query expression.Important points about im
    3 min read
  • C# | Type.GetTypeArray() Method
    Type.GetTypeArray() Method is used to get the types of the objects in the specified array. Syntax: public static Type[] GetTypeArray (object[] args); Here, it takes an array of objects whose types to determine. Return Value: This method returns an array of Type objects representing the types of the
    2 min read
  • C# Multidimensional Arrays
    Multidimensional arrays can be termed as arrays of arrays, extending the capabilities of one-dimensional arrays to store data in a structured format. Syntaxdata_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1][size2]….[sizeN]; Parameters: data_type: Type of dat
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences