Sign in to follow this  
Bevilacqua

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 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

Share this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this