+ 1

How can I make it so my code asks what kind of subclass its the one i want an object to be? C#

Sorry if my English is too shitty, the question would be: I have a base class RED, and from it 2 sub classes A and B. How can I express that when I creat an object let's say "p", instead of stablish the proper class this way: //RED p = new A (); it asks the user if the created object is either an A or a B? For example, I have a "character" class with 2 subclasses "mage" and "rouge". Can I ask the user to choose? how?

26th Jan 2018, 3:12 AM
Agustin Romano
Agustin Romano - avatar
6 odpowiedzi
+ 4
I'm working on a sample code for you to see this in action. Give me a few minutes.
26th Jan 2018, 4:07 AM
David Carroll
David Carroll - avatar
+ 11
Your English is fine, don't worry! ^_^ You can create the Character object, and instantiate it later once you know which type you want. Try this: Character p; //No "new" keyword yet! //Ask user which character they want //If they want a mage p = new Mage(); //else if they want a Rogue p = new Rogue();
26th Jan 2018, 3:43 AM
Tamra
Tamra - avatar
+ 3
And I complete the rest with an if/switch/do-while/ statement to make the choice? sorry I'm rather new in the world of programing! <3
26th Jan 2018, 3:47 AM
Agustin Romano
Agustin Romano - avatar
+ 3
Hey, thx man I just saw it, that was really useful and I learnt a few new things
26th Jan 2018, 5:18 AM
Agustin Romano
Agustin Romano - avatar
+ 3
@Agustin... This code demo should be useful in understanding how to conditionally instantiate sub classes and also evaluate those sub classes based on user input. https://code.sololearn.com/clvAW5RsP9qh/#cs Two Modes for Running Code: - Mode 1: User Input with any of the following 3 values: - A - B - Red - Mode 2: Leave input blank to run various static input tests.
26th Jan 2018, 5:25 AM
David Carroll
David Carroll - avatar
+ 3
Agustin... I'm glad it was useful. I might have gone overboard with my demo. :) However, I figured it might be good to demonstrate other concepts such as how to evaluate which type was created from both the sub class and the base class if the object is created based on user input. There are several concepts you could explore next from here. In the meantime, let me know if you have any questions about the demo.
26th Jan 2018, 5:40 AM
David Carroll
David Carroll - avatar