Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Lists with different type

Tags:

c#

.net

list

I want to add Lists with different types to a list. This is my approach:

struct Column
{
    public string title;
    public List<dynamic> col;
}

var signals = new List<Column>();
signals.Add(new Column {title = "stringCol", col = new List<string>() });
signals.Add(new Column {title = "doubleCol", col = new List<double>() });

It says that List<string> can't be converted to List<dynamic>. I also tried using templates, but I didn't get it running.

like image 789
Henste Avatar asked Sep 09 '25 11:09

Henste


1 Answers

Use object instead of dynamic, you will have list of object which you can later cast to desired type.

struct Column
{
    public string title;
    public List<object> col;
}

var signals = new List<Column>();
signals.Add(new Column {title = "stringCol", col = new List<object> {new List<string>() }});
signals.Add(new Column {title = "doubleCol", col = new List<object> {new List<double>() }});

Why not dynamic? read here: dynamic vs object type

Abstract:

If you use dynamic you're opting into dynamic typing, and thus opting out of compile-time checking for the most part.

So it means dynamic type will be calculated at runtime and it does not mean "any type" it means "some type defined at runtime"

like image 98
Kamil Budziewski Avatar answered Sep 11 '25 00:09

Kamil Budziewski