C
C#15mo ago
Livid

✅ dynamic list type

can you make a list like List<?>
21 Replies
Moods
Moods15mo ago
Wha You mean a list that can have any type of object?
Pobiega
Pobiega15mo ago
a List<T> can only have T in it. Thats the entire purpose of generics.
Moods
Moods15mo 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
Pobiega15mo 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
LividOP15mo ago
List<Any object>
Pobiega
Pobiega15mo ago
List<object> but as said above, that removes any and all benefits of using generics
Thinker
Thinker15mo ago
ArrayList
Pobiega
Pobiega15mo ago
iirc List<object> is actually prefered over ArrayList :d
Thinker
Thinker15mo ago
yes
Moods
Moods15mo 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
Pobiega15mo ago
Who knows 🙂
Livid
LividOP15mo ago
new List<object>() { "something" }; no worky :(
Moods
Moods15mo ago
With collection initializers you have to omit the ()
Thinker
Thinker15mo ago
no you don't
MODiX
MODiX15mo 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
Pobiega15mo ago
I'd like to know why you need a list with several different types in it, @Livid
Livid
LividOP15mo ago
i don
Moods
Moods15mo ago
Genuinely surprising Reading the docs it was always omitted so I assumed it was a necessity ? Whyd you ask then
Livid
LividOP15mo 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
Moods15mo ago
System.Collections.Generic Add a using statement for that namespace
Livid
LividOP15mo ago
yay
Want results from more Discord servers?
Add your server