Question

I'm currently developing a WPF project and most of my properties have two options to assign a value internally:

private int counter = 0;
public int Counter {
    get {
        return counter;
    }
    private set {
        counter = value;
    }
}
  1. Assigning via a private setter Counter = 1;

  2. Assigning the value directly to the private object counter = 1;

Which is the preferred way to assign a value internally (in the class itself)? Is there any benefit using one over another?

Was it helpful?

Solution

I would use the property. It will give you more flexibility if you find out that you have to change the property behavior later - you won't be able to do that using field.

btw. Why don't you use automatic property?

public int Counter { get; private set; }

You don't have to initialize field with 0. It's default value for int, so it will be done anyway.

OTHER TIPS

If the private set variables are required it is good to inject the properties in the constructor so that the object is initialized to the correct state. But if you are assigning a private variable after construction within a method, then you can set the variable directly:

counter++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top