C
C#10mo ago
Livid

✅ dynamic list type

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