user9409572
user9409572

Reputation:

unable to change the value of a property

I am currently improving my program that I posted on CR but I ran into a problem. I have a property called Total but when I try to set it to a value (0) it remains the same.

This is the property:

public class Player
{
    private int total;
    public int Total
    {
        get
        {
            total = 0;
            foreach (int card in hand)
            {
                total += card;
            }
            return total;
        }
        set { this.total = value; }
    }
}

And here is how I try to change it:

public class Game
{
    private void CompareHands()
    {
        //This is just for testing
        Console.WriteLine($"player total: {player1.Total}, is bust: {player1.Bust}");
        Console.WriteLine($"house total: {house.Total}, is bust: {house.Bust}");

        if (player1.Bust)
            player1.Total = 0;
        if (house.Bust)
            house.Total = 0;

        //this too
        Console.WriteLine($"player total: {player1.Total}, is bust: {player1.Bust}");
        Console.WriteLine($"house total: {house.Total}, is bust: {house.Bust}");
...
}

Also the Bust property if needed:

    private readonly int blackjack = 21;
    public bool Bust
    {
        get { return Bust = Total > blackjack; }
        private set { }
    }

Upvotes: 0

Views: 966

Answers (2)

Andrei U
Andrei U

Reputation: 1988

If I were you I would separate the Total calculation and Bust a bit differently:

public class Player
{
    public bool Bust { get; set; }

    public int GetTotal()
    {
        if (Bust)
        {
            return 0;
        }

        var total = 0;
        foreach (int card in hand)
        {
            total += card;
        }
        return total;
    }
}

A few things to notice:

  • the calculation is done in a method not a property - i think this is a cleaner way since a property is supposed to be quite simple and not have any logic in it
  • include Bust in the GetTotal calculation and return 0 if Bust is set to true
  • always compute the total value, unless you have a very good reason to have a cached version of it

Hope this helps.

Upvotes: 0

CodeNotFound
CodeNotFound

Reputation: 23190

Actually you're recalculating the total everytime you call the getter of your property.

A solution is to make the field total as Nullable<int> so if it is null, you do the logic you're doing actually otherwise return what is set in the field total.

public class Player
{
    private int? total; // <- Nullable<int> here
    public int Total
    {
        get
        {
            if(total.HasValue) // <- If value is set return that value.
            {
                return total.Value;
            }

            total = 0;
            foreach (int card in hand)
            {
                total += card;
            }

            return total.Value;
        }
        set { this.total = value; }
    }
}

Upvotes: 1

Related Questions