C
C#16mo ago
Alex Frost

❔ Change datatype during program execution

I have following two properties: private ContextType ExportContext = 0; private List<T> SelectedItems { get; set; } = new(); During execution, value of ContextType can be changed by user only if SelectedItems is empty. Based on value of ExportContext, I want to change the datatype T. Is that possible?
7 Replies
mtreit
mtreit16mo ago
For generics, T is typically known at compile time - it's not something you can just changes on the fly. If T is a base type and the types you want to change are both derived from that base type, then sure the underlying concrete type can be different. But you can't make a List<int> turn into a List<string> or anything like that.
Alex Frost
Alex FrostOP16mo ago
Could a List<object> fit in this?
mtreit
mtreit16mo ago
You can use a List<object>, yes. However, that's generally considered a questionable approach for a variety of reasons. Like performance can be quite poor because of boxing if you are dealing with primitive types, you are more likely to encounter issues at runtime instead of compile time, etc.
Alex Frost
Alex FrostOP16mo ago
Alright, thanks so much.
mtreit
mtreit16mo ago
Maybe consider having two strongly typed lists and swapping which one is in use based on the context?
Alex Frost
Alex FrostOP16mo ago
Yes, that's the fallback now.
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server