C# - Stuck

Started by
1 comment, last by Bevilacqua 13 years, 4 months ago
Hi all!

I'm beginning to learn C# and the book I'm using proposes a Lab to which they don't give the final code.
I'm not being able to figure out how to deal with this error ( pointed below with "HERE"). I know what it means and I already tried to initialize the myBet object when creating an instance to this class to see if it worked, but it didn't.
Anyway, I'm using the structure proposed in the book, where it is said to set the myBet field to null when initializing the Guy object and then, immediately, calling the updateLabels method, which should get a string from the myBet.getDescription.

I keep getting this error with myBet set to null and with myBet set to new Bet() when Guy is initialized. The only way I could avoid it was by initializing myBet inside the updateLabels method, but it must be initialized elsewhere.

How can I make use of myBet.getDescription() in this case?


namespace A_day_at_the_races
{
class Guy
{
public string name;
public Bet myBet;
public int cash;

public RadioButton myRadioButton;
public Label myLabel;

public void updateLabels()
{

------> //HERE :Object reference not set to an instance of an object.
myLabel.Text = myBet.getDescription();

myRadioButton.Text = name;
}

public void clearBet()
{
myBet.amount = 0;
}

public bool placeBet(int amount, int dog)
{
if (cash > amount)
{
myBet = new Bet() { bettor = this, amount = amount, dog = dog };
updateLabels();

return true;
}
else
Advertisement
public void updateLabels(){	if(myBet != NULL)		myLabel.Text = myBet.getDescription(); 	myRadioButton.Text = name;}

Wouldn't this work? Ofcource if you dont initialize it it will have undefined behaviour. So perhaps this is better:

public void updateLabels(){	if(myBet != NULL)		myLabel.Text = myBet.getDescription();	else		myLabel.Text = "";	myRadioButton.Text = name;}


dont know what getDescription does so can't give anything more specific.

Video Game Programmer.
5 years in industry.

Thanks. It worked. I had tried something similar, but I think I was using the ! operator in the wrong way.
Thanks again.

This topic is closed to new replies.

Advertisement