I've initialized an object '_currDie' in the Die class, ran an if statement to change the object to a derivative class object, then run a method.
The problem is that when it leaves the if statement, it seems to be reverting back to the base class.
namespace CharacterSheet
{
public partial class DiceRoller : Form
{
Die _currDie;
public DiceRoller()
{
InitializeComponent();
}
private void chooseSides_SelectedIndexChanged(object sender, EventArgs e)
{
if (chooseSides.SelectedItem.ToString() == "D4")
{
D4 _currDie = new D4();
}
if (chooseSides.SelectedItem.ToString() == "D6")
{
D6 _currDie = new D6();
}
if (chooseSides.SelectedItem.ToString() == "D8")
{
D8 _currDie = new D8();
}
if (chooseSides.SelectedItem.ToString() == "D10")
{
D10 _currDie = new D10();
}
if (chooseSides.SelectedItem.ToString() == "D20")
{
D20 _currDie = new D20();
}
if (chooseSides.SelectedItem.ToString() == "Percentile")
{
Percentile _currDie = new Percentile();
}
}
private void Roll_Click(object sender, EventArgs e)
{
_currDie.Roll();
string currResult = Convert.ToString(_currDie.RollResult);
MessageBox.Show(currResult);
}
}
}
Here is the base class
namespace CharacterSheet
{
public class Die
{
public int Sides { get; set; }
private Random rng = new Random();
public int rollResult;
public int RollResult
{
get
{
return rollResult;
}
}
public virtual void Roll()
{
rollResult = rng.Next(Sides) + 1;
}
}
}
And the derivative class I've been testing with
namespace CharacterSheet
{
public class D4:Die
{
public D4 ()
{
Sides = 4;
}
}
}
I set break points at the first if statement and as I step through I can clearly see that _currDie changes from a D4 object to a Die object on the _currDie.Roll(); At which point I get a System.NullReferenceException
I've tried instantiating _currDie without defining the class, but then the method gets errors because there is no Roll method for the object.
In each of your if
statements, you're declaring a new local variable, e.g.
if (chooseSides.SelectedItem.ToString() == "D4")
{
D4 _currDie = new D4();
}
That initializes the new _currDie
variable, but then you hit the end of the block, and so it's useless. What you want to do is assign a new value to the existing field:
if (chooseSides.SelectedItem.ToString() == "D4")
{
_currDie = new D4();
}
Note the lack of the declaration here, because you're not trying to declare a new variable. You're just assigning a value to an existing variable.
As an aside, if nothing else you would be better off with a switch statement:
switch (chooseSides.SelectedItem.ToString())
{
case "D4": _currDie = new D4(); break;
case "D6": _currDie = new D6(); break;
case "D20": _currDie = new D20(); break;
...
}
I'd personally do something slightly different, probably having a Dictionary<string, Func<Die>>
but that's a different matter.
See more on this question at Stackoverflow