C# - Stuck

Recommended Posts

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 Label myLabel;

public void updateLabels()
{

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

}

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

Share on other sites
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.

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

Create an account

Register a new account

• Forum Statistics

• Total Topics
628294
• Total Posts
2981876

• 11
• 10
• 10
• 11
• 17