-2

I have a class in C# defined as

 public class Square{
   public int Count{ get; set; }
}

I want to set in Count properties the amount of calls it has.

I set in the constructor

public Square()
{
    Count+= 1;
}

But it is always 0, when I call it.

How can I keep the value for next calls.?

Thanks

3
  • Please update the question to include a minimal reproducible example which demonstrates the problem you are trying to describe. Commented Mar 31 at 19:01
  • Do you mean you want the Count to be incremented every time you retrieve the property? Commented Mar 31 at 19:09
  • 1
    You, probably, want static property public static int Count {get; private set;} Commented Mar 31 at 19:29

1 Answer 1

0

If I've understood you right, you want to increment Count each time you call the constructor (to count created instances). If it's your problem, you can make Count being static, i.e. one property for all instances:

public class Square {
  // Note "static" 
  public static int Count{ get; private set; }

  public Square() {
    Count += 1; 
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.