Creating a Generic<T> type instance with a variable containing the Type

C#GenericsTypesInstance

C# Problem Overview


Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?

Type k = typeof(double);
List<k> lst = new List<k>();

C# Solutions


Solution 1 - C#

Yes, there is:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);

Solution 2 - C#

A cleaner way might be to use a generic method. Do something like this:

static void AddType<T>()
    where T : DataObject
{
    Indexes.Add(typeof(T), new Dictionary<int, T>());
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - C#David MView Answer on Stackoverflow
Solution 2 - C#Bryan LegendView Answer on Stackoverflow