❔ 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
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.
Could a List<object> fit in this?
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.
Alright, thanks so much.
Maybe consider having two strongly typed lists and swapping which one is in use based on the context?
Yes, that's the fallback now.
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.