Eric Anastas
Eric Anastas

Reputation: 22213

Can a type parameter of a generic class be set dynamically through a Type instance?

I want to do something like the code below.

    public IList SomeMethod(Type t)
    { 
        List<t> list = new List<t>;
        return list;
    }

This, of course, does not work. Is there some other way I can dynamically set the type parameter of a generic class using a reference to a Type instance?

Upvotes: 0

Views: 3317

Answers (4)

Joel Coehoorn
Joel Coehoorn

Reputation: 415881

You have to use the Type.MakeGenericType() method along with Activator.CreateInstance().

The resulting code is ugly, slow, and opens you up to run time failures for things that you would normally expect to catch at compile time. None of these have to be a huge deal, but I've seen the last one especially catch other .Net developers (who expect full type safety) off guard.

Personally, I've never done it this way. Every time I've been tempted I've taken it as an indication that there's a problem with my design and gone back to the drawing board. I've not regretted that course.

Upvotes: 4

Stu
Stu

Reputation: 15769

No additional information here, just for those-that-follow sandbox code (I had to try it all out)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListFromType
{
    class Program
    {
        static void Main(string[] args)
        {
            var test1 = FlatList(typeof(DateTime));
            var test2 = TypedList<DateTime>(typeof(DateTime));
        }

        public static IList<T> TypedList<T>(Type type)
        {
            return FlatList(type).Cast<T>().ToList();
        }

        public static IList FlatList(Type type)
        {
            var listType = typeof(List<>).MakeGenericType(new Type[] { type });
            var list = Activator.CreateInstance(listType);
            return (IList) list;
        } 
    }
}

Upvotes: 1

Richard Smith
Richard Smith

Reputation: 537

Try this:

public IList SomeMethod(Type t)
{ 
    Type listType = typeof(List<>);
    listType = listType.MakeGenericType(new Type[] { t});
    return (IList)Activator.CreateInstance(listType);
}

Upvotes: 7

Zain Shaikh
Zain Shaikh

Reputation: 6043

can you try doing like following, it is generic type,

    public IList SomeMethod<T>(T t)
    {
        List<T> list = new List<T>();
        list.Add(t);
        return list;
    }

Upvotes: -1

Related Questions