CSharp - LINQ ToArray

Introduction

The ToArray operator creates an array of type T from an input sequence of type T.

Prototypes

public static T[] ToArray<T>(
  this IEnumerable<T> source);

This operator takes an input sequence named source, of type T elements, and returns an array of type T elements.

Exceptions

ArgumentNullException is thrown if the source argument is null.

The following code will create a sequence of that type by calling the OfType operator on an array.

Once we have that sequence, we can call the ToArray operator to create an array.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w ww . j a  v  a 2 s  .c  om
{
    static void Main(string[] args)
    {
         string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
         string[] names = codeNames.OfType<string>().ToArray();
    
         foreach (string name in names)
           Console.WriteLine(name);
    }
}

Result

First we convert the codeNames array to a sequence of type IEnumerable<string> using the OfType operator.

Then we convert that sequence to an array using the ToArray operator.

Since the ToArray is a non deferred operator, the query is performed immediately.