C
C#2y ago
Livid

✅ dynamic list type

can you make a list like List<?>
21 Replies
Moods
Moods2y ago
Wha You mean a list that can have any type of object?
Pobiega
Pobiega2y ago
a List<T> can only have T in it. Thats the entire purpose of generics.
Moods
Moods2y ago
If you really want to have a workaround you’d have to make T an
object
object
I did not format that well
Pobiega
Pobiega2y ago
Downside of that is you'd need runtime type checking to actually do anything useful with the item
foreach(var item in list)
{
if(item is int i)...
if(item is string s)...
foreach(var item in list)
{
if(item is int i)...
if(item is string s)...
Livid
LividOP2y ago
List<Any object>
Pobiega
Pobiega2y ago
List<object> but as said above, that removes any and all benefits of using generics
Thinker
Thinker2y ago
ArrayList
Pobiega
Pobiega2y ago
iirc List<object> is actually prefered over ArrayList :d
Thinker
Thinker2y ago
yes
Moods
Moods2y ago
Indeed it is, also this is outside the scope of this post but how does the ArrayList.Sort function even work Like it can have different type of objects what’s it sorting based on
Pobiega
Pobiega2y ago
Who knows 🙂
Livid
LividOP2y ago
new List<object>() { "something" }; no worky :(
Moods
Moods2y ago
With collection initializers you have to omit the ()
Thinker
Thinker2y ago
no you don't
MODiX
MODiX2y ago
Thinker
REPL Result: Success
new List<object>() { "something" }
new List<object>() { "something" }
Result: List<object>
[
"something"
]
[
"something"
]
Compile: 386.597ms | Execution: 72.199ms | React with ❌ to remove this embed.
Pobiega
Pobiega2y ago
I'd like to know why you need a list with several different types in it, @Livid
Livid
LividOP2y ago
i don
Moods
Moods2y ago
Genuinely surprising Reading the docs it was always omitted so I assumed it was a necessity ? Whyd you ask then
Livid
LividOP2y ago
comboBox1.DataSource = new List<object>() { "something" }; Error Code: CS0246 -> Description: The type or namespace name 'List<>' could not be found (are you missing a using
Moods
Moods2y ago
System.Collections.Generic Add a using statement for that namespace
Livid
LividOP2y ago
yay

Did you find this page helpful?