KuysChan
KuysChan

Reputation: 1

Dynamically Add Values from Property

I was wondering if I can dynamically add values set in property using override method. I want to add the values (scores) from properties so that in the end, I can get the total points.

here my code

public abstract class player
    {
        public string nickName { get; set; }


        public virtual int computeScore()
        {
            throw new NotImplementedException();
        }
    }

public  class Bes : player
    {
        public int initScore =0;

        public int score { get; set; }
        public int ttlScore { get; set; }


        public override int computeScore()
        {
            return this.ttlScore += this.score;
        }
    }

Upvotes: 0

Views: 72

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

It's doubtful that want you want to do is a good idea. But the fact is, it's not really clear what you want to do.

I have a vague sense that you want, every time the score property is set, to add the value to the ttlScore property. If so, then sure...you can do that, but it's a terrible idea. Using a property to represent that operation would be extremely confusing; instead, you should have a method, e.g. named AddScore(), so it's clear reading the code that every time a score is passed to the method, it will be added to the running total.

For example, something like this:

public  class Bes : player
{
    public int MostRecentScore { get; private set; }
    public int TotalScore { get; private set; }

    public int AddScore(int score)
    {
        this.MostRecentScore = score;
        return this.TotalScore += score;
    }
}

Then the MostRecentScore property will still show whatever the most recent score was, while the TotalScore property will show the running total, but the class members make it clear that you must call AddScore() to report a new score, and that this will take care of updating both properties of interest.

This example of course does not use the virtual aspect of your code example. It's not clear from your question why the computescore() method was in fact made virtual, and it probably doesn't need to be — if you really want the base class to know about scoring, then the score-related properties belong there as well, and none of the members need to be virtual — so I've left it out.

If this does not address your question, please edit your question so that it's more clear what you're trying to do. Provide a good Minimal, Complete, and Verifiable code example that shows clearly what you've tried, along with a detailed and specific explanation of what the code does, and what you want it to do instead.

Upvotes: 1

Related Questions