melika melika - 1 month ago 12
C# Question

How to construct an object using a variable as the class name?

I am creating a game in C# Windows form and I will have 9 different characters inside the game for my player to choose from (using radio buttons). I have a variable called PlayerChar and Whenever the player chooses a character I will store the character's name inside that variable. Also I have 9 different classes for each characters. What I am trying to do is, to get the program to create an object from the class of the character chosen. but I don't know how to use variable PlayerChar as my class name.

PlayerChar obj = new PlayerChar();


This is basically what I am trying to do. Also I tried using Activator.CreateInstance:

PlayerChar myObj = Activator.CreateInstance(PlayerChar);

Answer

Have PlayerChar be the base class for all of your character classes.

public class PlayerChar
{
    ...
}

public class WarriorChar : PlayerChar
{
    ...
}

public class RangerChar : PlayerChar
{
    ...
}

public class ClericChar : PlayerChar
{
    ...
}

Then use a switch block or sequential if blocks to instantiate your player object with the right character subclass.

PlayerChar myObj = null;

if (warriorButton.IsSelected)
    myObj = new WarriorChar();
else if (rangerButtom.IsChecked)
    myObj = new RangerChar();
else if (clericButton.IsChecked)
    myObj = new ClericChar();
...

(Don't use the Activator class to instantiate your objects unless you fully understand what Activator does and have a well-thought-out reason for using it. Nine times out of ten it is used by people trying to get fancy with their code and end up just overcomplicating things.)

Comments