LateCast

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Console2017.Mains
{
    static class MapToCollection
    {
        static public object LateCast(this ICollection items, Type itemType)
        {
            var methodDefintionForCast = typeof(System.Linq.Enumerable)
                .GetMethods(BindingFlags.Static | BindingFlags.Public)
                .Where(mi => mi.Name == "Cast")
                .Select(mi => mi.GetGenericMethodDefinition())
                .Single(gmd => gmd != null && gmd.GetGenericArguments().Length == 1);

            var method = methodDefintionForCast.MakeGenericMethod(new Type[] { itemType });
            return method.Invoke(null, new[] { items });
        }


        static public IEnumerable ConvertToGeneric(this ICollection source, Type collectionType)
        {
            return source.LateCast(collectionType.GetGenericArguments()[0]) as IEnumerable;
        }
    }

    public class Program
    {
        public void Main()
        {
            var input = new LinkedList<string>();
            input.AddFirst("Test1");
            input.AddLast("Test2");
            
			object output = input.ConvertToGeneric(typeof(ICollection<string>));

            foreach (var item in output as IEnumerable) Console.WriteLine("Here it is: {0}", item);
        }
    }
}
;