❔ Create new instance of type unknown at runtime?
Say I have a base class,
abstract class Letter
with child classes A
, B
, and C
.
If I have a variable: Letter myLetter
which is of unknown type (can be any of A
, B
, or C
, the only guarantee is it's a child of Letter
), how can I create a new instance of whatever class myLetter
is?
I need to create a new instance (must call default constructor as well) of whatever myLetter
is and store it in another variable (say myLetter2
)26 Replies
So, basically,
?
Yes
Not gonna lie, I wonder why you'd need to do that, but aight
The one and only way I can think of is reflections
Ah, I figured
Activator.CreateInstance(myLetter.GetType())
should workAngius
REPL Result: Success
Result: bool
Compile: 531.005ms | Execution: 44.365ms | React with ❌ to remove this embed.
Yeah, seems to work file
Wondering as well if there was another way. In reality I have a reagent clasd which stores properties of the reagent including amount. When I move reagent from one container to another I need to remove the correct quantity from one container (changing its amount variable) and then add a new reagent instance of whatever type the reagent instance is from the first container, set the amount properly and store it I another container
Uh, ca't you just do
?
So you have
And you need to be able to represent a change of state to:
Correct?
If I move 100% of the reagent yes, otherwise a new reagent instance is necessary.
Yes
This sounds like your reagents should not be C# types
Wuh oh
I'd have one Reagent type, which has an enum value-ed member
ReagentType
, and an amount.Or should be stored differently, although maybe I'm thinking too much in database terms to be introducing many-to-many lol
what happens if you put 2 of the same reagent into a container?
Whenever a reagent is added a method,
CombineLikeReagents()
which adds their quantities togethermy quick sketch, might be useful, might not be. It's here :P
Nice. Yes what I have going on is very similar. My previous version used a class in place of an enum (since different reagents have special properties) but was otherwise identical. Previously all combining was done in an addreagent method as well, but I never made on for the slightly newer version
have special propertiesWhat do these properties look like? (Literal C# properties?)
No, methods that define how a reagent might react with another. The base class has a react method, overridden by a child.
Aha, I think I have the solution
one moment, sketching
Each reagent can be responsible for creating the new one:
Ah true
That would work
If the
Take
is always the same for all, can do some generic stuff:
alright, I stop spam now hahaA generic is clever there
Nw, thanks for the help
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.