user2929108
user2929108

Reputation:

Display text in a string based on boolean value

This is the line causing the issue:

lblClimberInfo.Text = selectedClimber + "\r\n" + "Finished: " + selectedClimber.HasFinished ? "Yes" : "DNF" + "\r\n" + "Time: " + selectedClimber.Hours.ToString("00") + ":" + selectedClimber.Minutes.ToString("00") + ":" + selectedClimber.Seconds.ToString("00");

From my main class:

private bool hasFinished;

public bool HasFinished
{
    get { return hasFinished; }
    set { hasFinished = false; }
}

I want it so that it says Finished: Yes if the HasFinished bool is true and display Finished: DNF if the HasFinished bool is false and display that. At the minute, it displays Finished: False by default but when I click a button that runs a method that essentially changes the bool, instead of saying Finished: True it just says Finished:.

I want to be able to customise it instead of it outputting True or False

Upvotes: 0

Views: 1044

Answers (1)

Simon Forsberg
Simon Forsberg

Reputation: 13341

Because of operator precedence issues, put parenthesis around ternary operators. Otherwise the "Time" will only show if HasFinished is false.

lblClimberInfo.Text = selectedClimber + "\r\n" + "Finished: " + (selectedClimber.HasFinished ? 
  "Yes" : "DNF") + "\r\n" + "Time: " + selectedClimber.Hours.ToString("00") + ":" + 
  selectedClimber.Minutes.ToString("00") + ":" + selectedClimber.Seconds.ToString("00");

Also, your setter is quite interesting:

private bool hasFinished;

public bool HasFinished
{
    get { return hasFinished; }
    set { hasFinished = false; }
}

It seems like it is impossible for HasFinished to be true, unless you modify the private variable somewhere else in your class. But instead of having a setter that sets the property to false always, it is better to omit the setter and thus making the property read-only. You might want to read up on Using Properties in C#

To define a correct setter, use this instead:

    set { hasFinished = value; }

Upvotes: 1

Related Questions