I need to code a rogue-like game as a project, but I have a slight problem. There is a time I need to choose between which object to create using a switch. I want to declare an “empty” object outside of the switch and the switch then fills the object with values. This is kind of what I want to do:
Console.WriteLine("What race would you like to be?")
int answer = Convert.ToInt32(Console.ReadLine());
Object heroRace; // This is where the problem comes in
switch(answer)
{
case 1: heroRace = new Orc(); break;
case 2: heroRace = new Elf(); break;
}
I want heroRace to be outside of the switch scope for re-usage. It would greatly simplify my program if I could create something like that.
You need to cast the object to more concrete type before accessing it’s members
But this can lead to casting exception.
For example..
would lead to a casting exception because
ois an object ofOrcnotElf.It’s better to check if the object belongs to a particular class before casting using
isoperatorObjectitself is not useful unless you override theToString,GetHashCode.. methodsIt should be like
OrcandElfshould be subclass ofLivingThingBaseClassLivingThingBaseClasscan contain methods likemove,speak,kill..All or some of these methods would be overridden byOrcandElfLivingThingBaseClasscan be anabstractclass or even aninterfacedepending upon your requirement