Reputation: 7908
From what I can tell, properties are used to provide accessor method-esque functionality; however, they do so at the cost of normal method inheritance behavior. Are there any advantages to using properties versus conventional setter/getter methods? What are the pros/cons of properties and accessor methods?
Upvotes: 1
Views: 1048
Reputation: 41246
I think you might be confused. In your examples, the above methods should be accessible. For example, given this set of types, the following should work:
public class Base
{
public virtual int Datum { get; set; }
}
public class Derived : Base
{
public override int Datum
{
get { return 12; }
// set method remains as normal, with just the get overriden
}
public void SetDatumMethod(int newValue)
{
Datum = newValue; // Datum as a property is still accessible
}
}
The derived class still inherits the property. Properties really are just syntactic sugar in C# (mostly), as the compiler is generating set_Datum(int x)
and get_Datum()
methods behind the scenes for you. The property get/set methods can still be overridden individually as shown above.
The advantage of using properties is that they have additional semantic meaning; they "contain" or "represent" data in some fashion, not a method for generating the data.
Upvotes: 1
Reputation: 28980
Visual Studio debugger executes the getter method when watching an object. That is, property accessors are executed at unpredictable times and should thus not cause any discernable side-effects. Abusing properties can lead to difficult bugsto resolve .
Another reason to use a method is that order retrieval is likely to be parameterized.
A good practice is for property access to be computationally cheap; client code should not be forced to place the property value into a local variable - it's premature optimization.
Upvotes: 0