Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array. Avoid mutating the return value. - CSharp System

CSharp examples for System:Array Convert

Description

Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array. Avoid mutating the return value.

Demo Code

// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;

public class Main{
        /// <summary>
        /// Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array. 
        /// Avoid mutating the return value.
        /// </summary>
        public static T[] AsArray<T>(this IEnumerable<T> values)
        {/*from  ww  w  .ja va 2s  . c o  m*/
            Contract.Assert(values != null);

            T[] array = values as T[];
            if (array == null)
            {
                array = values.ToArray();
            }
            return array;
        }
}

Related Tutorials