Is there a reason not to use "protected" properties?

Just wondering...

Are there any reasons not to use protected properties?

I mean instead:

public abstract class Foo { protected Bar { get; private set; } } 

to use this:

 public abstract class Foo { private Bar _bar; protected Foo(Bar bar) { _bar = bar; } protected GetBar() { return _bar; } } 
+6
protected c #
source share
4 answers

I see no reason why you would use the GetXXX() method instead of a property, regardless of its modifiers.

Since you tagged this question with a C# tag, I strongly recommend using the first approach. This requires properties.

Use the method only when the value returned by it can be different each time it is called, regardless of its state. For example, DateTime.Now was an error and should have been a method.

See Property Usage Guidelines on MSDN for more information. On the other hand, it is surprising that they did not need to change it from Framework 1.1 .

+9
source share

A few reasons to use properties instead of methods:

  • Data binding can only see properties
  • You can use read only or write semantics only.
+1
source share

Only if in class

there are non-attributable or unreadable attributes,
0
source share

The question is not what he has more about protected : why use properties?

Propeties are logically equivalent with pairs of Getter / Setter methods, no matter what you do with a using Name {get{} \ set{}} , which you can do with a pair of GetName() \ SetName() and vice versa, especially since C # has an accessory getter and setter, so we can play with accessibility too.

But there are people who believe that public (or protected) properties are a bit like a hoax from the point of view of OOP, especially if everything that does this property simply exposes a field of support. In the end, person.Name = "SWeko" seems to change the state of the object from the outside, and person.SetName("SWeko") simply tells the object that it needs to change its state. And from a purely theoretical point of view, I believe that these objections deserve attention.

However, not all of us have the luxury of living in ivory towers, so the concept of properties is really useful, because it is more readable, less error prone and IMHO, closer to the real world model. It also gives us some dichotomy when I write something like this:

 person.Name = "SWeko"; person.Work(); 

I expect the first line to be quickly assigned and not have any side effects, while I expect the second line to do something else and possibly affect the internal state of the object. When I use the Getter and Setter methods, this difference is not obvious:

 person.SetName("SWeko"); person.Work(); 
0
source share

All Articles