What is the situation to choose?

In particular:

  • If I only need to get the value of a variable, use a getter or a property?
  • If only assign - similarly, a setter or a property?
  • If there is no underlying at all (I don’t know how to translate) a variable, but the value is calculated?

While I was gone, the question was edited. Why is Task.Result a property, not a method? What should be put and why? It has only a getter and it is not cached (probably).


Related question: What are properties for?

  • four
    This question can be given a concise answer, moreover - a chapter in the Framework Design Guidelines is devoted to it. 4 out of 5 voters do not even have a C # plate in the profile, have a conscience! - PashaPash ♦
  • @PashaPash: I think they close mostly for the quality of the issue design - just 1 line. It is necessary to add MORE details to the question, identify the essence of the problem, and not just ask "which is better, horse or pluto, which is better to choose" - Kromster
  • one
    @KromStern: for those familiar with C #, this is not a “horse and pluto”, but two horses of different breeds. - Nick Volynkin ♦
  • @PashaPash, the reason for closing was initially selected and was not successfully chosen, but the “edit required” verdict fits here. The question in the current formulation does not fit the SO format, so it needs editing. And here it does not matter if there is c # in the profile or not. - BOPOH
  • 2
    The @BOPOH question for those who know C # is sufficiently clear and unambiguous. And it occurs when java goes to C # - because in java, instead of properties, methods are used. This is a standard novice question. From the category "how to send mail in php". And it can be given a "clear and concise" answer. I do not understand what edit you would like to see. - PashaPash ♦

5 answers 5

Methods are actions. Properties are data.

The question is discussed in detail in MSDN: Property Usage Guidelines: Properties vs. Methods

If what you write looks like a piece of object data - make it a property. For example, Control.Name.

If what you write:

  • converts data ( .ToString() )
  • takes a long time
  • gives side effects when getting
  • produces different results for two calls in a row
  • depends on the order of calling other properties or methods
  • static, but can return different results
  • returns array

you should use the method.

  • one
    Properties are also methods. Properties are compiled into methods - heteras and setters, and theoretically even a heter and a seter can be with more than one parameter, because they are the most common methods with all their charms, and it works if you write on IL, but in C # do not write such a construction. - Alexander Vasilyev
  • 2
    I would answer this way: properties are a more convenient way of writing the GetSomeValue () and SetSomeValue (value) methods. Accordingly, answering the author's question: for convenience and conciseness, it is worth using properties instead of methods if their semantics are GetValue and SetValue (value). - Alexander Vasilyev
  • one
    @AlexanderVasilyev post your comment as an answer? - PashaPash ♦
  • one
    In general, you need to make one wiki-answer and supplement everything - Kromster
  • one
    @AlexanderVasilyev: this is because the question has been closed. Now it is rediscovered. chat.stackexchange.com/transcript/message/23103058 # 23103058 , stackoverflow.com/posts/438747/revisions - Nick Volynkin ♦

From the point of view of runtime there is no difference, of course. A property is nothing more than a pair of two functions — a getter and a setter; moreover, these functions, formally speaking, are not at all obliged to read / establish any field of the object.

There is a difference in semantics. When we talk about an object, we mean an abstraction of something from the outside world. This sounds rather trivial, but this leads to non-trivial conclusions.

An object has data that it possesses, and a behavior . What is data is modeled by properties. What is behavior is modeled by methods. At the same time, it does not matter at all whether the object data is represented by a field, several fields, or is calculated on the fly at all — these are implementation details that are not interesting to anyone “outside”. This is one of the reasons why properties should be set out, not fields .

Let's say you have a dog. She has a coat color, a nickname, and she knows how to execute commands. Now let's look at the difference.

A nickname is a property of a dog: it is something that is an object (line) inherent in the dog itself. It can be installed (for example, the new owner of the dog can change the nickname), and read. Accordingly, it needs to be modeled by the property:

 public string Name { get; set; } 

The dog's coat color is also its property. But it is impossible to "install" it outside (let's digress from the possibility of repainting the dog: the color of the paint and the color of the coat are not the same). Therefore, it must be modeled with a property that is read-only:

 private readonly Color color; public Color Color { get { return color; } } 

(or for C # 6 that was released a couple of days ago, you can simply

 public Color Color { get; } 

since the value can be set in the constructor).

Now, the execution of the command. This is not a property of the dog itself, it is her behavior. Thus, it will be correct to model the execution of a command like this:

 public void ExecuteCommand(DogCommand command) { ... } 

Notice that the formal attributes (“I just get the value of the field!”) Are irrelevant. For example, if you have a team that is currently being executed by a dog, it is recorded in the inner field, and you want to be able to find out which command the dog is performing at the moment, it will be wrong to issue a command like this:

 private DogCommand currentCommand = null; public DogCommand CurrentCommand { get { return currentCommand; } set { if (currentCommand != null) StopExecuting(); currentCommand = value; if (currentCommand != null) StartExecuting(); } } 

because the team is not an inherent property of the dog itself, but only its behavior. For example, it would be correct to:

 bool isExecutingCommand = false; DogCommand currentCommand = null; public void ExecuteCommand(DogCommand command) { if (isExecutingCommand) CancelCommand(); isExecutingCommand = true; currentCommand = command; StartCommand(command); } public DogCommand GetCurrentExecutingCommand() { return isExecutingCommand ? currentCommand : null; } 

    Properties are also methods. Properties are compiled into methods - heteras and setters, and even heters and setters can be with more than one parameter, because they are the most common methods with all their charms, but you cannot write such a construction in C #, but on IL or VB please: https://msdn.microsoft.com/en-us/library/bc3dtbky.aspx

    So, properties are a more convenient way to write the GetSomeValue () and SetSomeValue (value) methods. Accordingly, answering the author's question: for convenience and conciseness, it is worth using properties instead of methods if their semantics are GetValue and SetValue (value).

      There is no absolutely correct answer to this question, therefore everything that will be written as answers is nothing more than opinions.

      So, personal opinion: properties allow you to simplify work with the object. By and large, whenever possible, it is better to use properties instead of methods, except in a few cases.

      For example, the possibility is, if you have a method without parameters returning some value without changing the state of the object - this property is read-only. It does not matter here whether the normal hidden field or the result of the calculation is returned.

      As for the exceptions, they are as follows: sometimes in order to comply with encapsulation, you should not allow changing individual properties of an object. A pair or triple of properties must always be changed together and matched to ensure the invariance of the object. In this case, you can make these properties read-only and add a method with two to three parameters that checks the validity of the invariant at the input.

      Another exception concerns the execution time of calculations. If the time may be “large enough”, it is more correct to write a method, not a property. As far as I understand, the thing is in “psychology”: when you see Tree.Depth , the construction is perceived as the usual getting the field value, although in reality it can be a recursive method with a long execution time.

        Since the properties themselves are nothing more than "sugar", this is often a matter of personal preference, but on the whole, everything has been correctly written by PashaPash. Properties should look like they are the fields of your object, the properties only allow you to hide them conveniently. Specifically for your questions:

        • As a rule property.
        • Although this is possible, it is not recommended to create write-only properties, therefore in this case the method is recommended.
        • It depends on the method of calculation, in the general case, if only other properties are used (ie, static data of the object), then the property, otherwise - the method.
        • These were my questions already, but thanks)) - Nick Volynkin ♦

        Protected by member Nick Volynkin ♦ 7 Sep '15 at 8:17 .

        Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

        Maybe you want to answer one of the unanswered questions ?