C
C#2y 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
mtreit2y 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 FrostOP2y ago
Could a List<object> fit in this?
mtreit
mtreit2y 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 FrostOP2y ago
Alright, thanks so much.
mtreit
mtreit2y ago
Maybe consider having two strongly typed lists and swapping which one is in use based on the context?
Alex Frost
Alex FrostOP2y ago
Yes, that's the fallback now.
Accord
Accord2y 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.

Did you find this page helpful?