Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dynamic type List<T>

I don't want my List to be of fixed type. Rather I want the creation of List to be dependent on the type of variable. This code doesn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            string something = "Apple";

            Type type = something.GetType();

            List<type> list = null;

            Console.ReadKey();

        }
    }
}

Can anybody tell me what changes I need to make in order to make it work right? I want the creation of list to be dependent on the type of variable something

like image 864
Jaggu Avatar asked Mar 25 '12 13:03

Jaggu


People also ask

Can a list be dynamic?

A dynamic list is any list that changes as the subject it covers changes. Therefore, it may never be completed. A list of any type may be dynamic.

What is dynamic datatype?

The IDL language is dynamically typed. This means that an operation on a variable can change that variable's type. In general, when variables of different types are combined in an expression, the result has the data type that yields the highest precision.

What are dynamic types in C#?

The dynamic type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object . At compile time, an element that is typed as dynamic is assumed to support any operation.

How do you create a list in C sharp?

The following example shows how to create list and add elements. In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.


3 Answers

string something = "Apple";
Type type = something.GetType();
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);

This is how you create a list of statically unknown type. But notice that you are unable to mention the runtime type of the list statically. You have to use a non-generic type or even object.

Without knowing more about what you want to accomplish this is the best you can do.

like image 127
usr Avatar answered Oct 21 '22 20:10

usr


I want type safety but I need dynamic type safety.

If you mean you want runtime type-safety, you can create List<T> using reflection (see usr's answer) or dynamic and then treat it as the non-generic IList.

Using dynamic, it would look something like this:

static List<T> CreateListByExample<T>(T obj)
{
    return new List<T>();
}

…

object something = "Apple";

IList list = CreateListByExample((dynamic)something);

list.Add(something); // OK

list.Add(42);        // throws ArgumentException
like image 6
svick Avatar answered Oct 21 '22 20:10

svick


The dynamic and reflection all work fine - but with a downside on performance - and losing strong typing, code design / clarity etc.
i.e. you should always try and resolve things w/o it - if you can, your code allows it...
So, and (note) depending (very much) on your specific code, needs,
you could also use a 'trick' to 'infer' the type and make it generic...

class Program
{
    static void Main(string[] args)
    {
        string something = "Apple";
        int test = 5;
        var list = something.GetList();
        var listint = test.GetList();
        Console.WriteLine(list.GetType());
    }
}
static class Extension
{
    public static List<T> GetList<T>(this T value)
    {
        return new[] { value }.ToList();
    }
}

...i.e. if you have a value for a variable and before 'entering' the generic context,
you could use extensions (which are very helpful with around this), and let it infer the type and a list type for you
NOTE: this 'work around' unfortunately doesn't always pan out and when your code is 'too dynamic' (I know this is not too 'exact' but out of scope for this) and if it's depending on the reflection induced types etc.
i.e. there isn't a clean-cut solution, this is just an example, you'd need to put some sweat into it :) to make it work for you - e.g. you may require a wrapper type here and there and obviously creating a list in this way might not be what you want etc.

like image 1
NSGaga-mostly-inactive Avatar answered Oct 21 '22 20:10

NSGaga-mostly-inactive