Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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++;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top