Wraps the provided enumerable into a ReadOnlyCollection{T} Copies all of the data into a new array - CSharp System

CSharp examples for System:Array Create

Description

Wraps the provided enumerable into a ReadOnlyCollection{T} Copies all of the data into a new array

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using System.Runtime.CompilerServices;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

public class Main{
        /// <summary>
        /// Wraps the provided enumerable into a ReadOnlyCollection{T}
        /// //from w ww.jav  a 2  s.c  o m
        /// Copies all of the data into a new array, so the data can't be
        /// changed after creation. The exception is if the enumerable is
        /// already a ReadOnlyCollection{T}, in which case we just return it.
        /// </summary>
        [Pure]
        public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> enumerable)
        {
            if (enumerable == null)
            {
                return EmptyReadOnlyCollection<T>.Instance;
            }

            var troc = enumerable as TrueReadOnlyCollection<T>;
            if (troc != null)
            {
                return troc;
            }

            var builder = enumerable as ReadOnlyCollectionBuilder<T>;
            if (builder != null)
            {
                return builder.ToReadOnlyCollection();
            }

            var collection = enumerable as ICollection<T>;
            if (collection != null)
            {
                int count = collection.Count;
                if (count == 0)
                {
                    return EmptyReadOnlyCollection<T>.Instance;
                }

                T[] clone = new T[count];
                collection.CopyTo(clone, 0);
                return new TrueReadOnlyCollection<T>(clone);
            }

            // ToArray trims the excess space and speeds up access
            return new TrueReadOnlyCollection<T>(new List<T>(enumerable).ToArray());
        }
}

Related Tutorials