Copies s in an array to an object array - CSharp System

CSharp examples for System:Array Convert

Description

Copies s in an array to an object array

Demo Code


using System.Collections.Generic;
using System.Collections;

public class Main{
        /// <summary>
        /// Copies <typeparamref name="T"/>s in an array to an object array
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="array">the source array</param>
        /// <returns>An array of objects</returns>
        public static TOut[] Cast<TIn,TOut>(TIn[] array)
        {/*from   ww  w . j  av a  2 s .com*/
            var res = new TOut[array.Length];
            System.Array.Copy(array, res, array.Length);
            return res;
        }
        /// <summary>
        /// Executes a function on each item in a <see cref="ICollection{TIn}" />
        /// and returns the results in a new <see cref="IList{TOut}" />.
        /// </summary>
        /// <param name="coll"></param>
        /// <returns></returns>
        public static IList<TOut> Cast<TIn, TOut>(ICollection<TIn> coll)
            where TIn: class
            where TOut : class
        {
            IList<TOut> result = new List<TOut>(coll.Count);
            foreach (var obj in coll)
                result.Add(obj as TOut);
            return result;
        }
        /// <summary>
        /// Executes a function on each item in a <see cref="ICollection" />
        /// and returns the results in a new <see cref="IList" />.
        /// </summary>
        /// <param name="coll"></param>
        /// <returns></returns>
        public static IList<T> Cast<T>(ICollection coll)
        {
            IList<T> result = new List<T>(coll.Count);
            foreach (var obj in coll)
                result.Add((T)obj);
            return result;
        }
}

Related Tutorials