Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I prefer property over method?

Tags:

c#

.net

c#-4.0

When should I prefer property over method ? Because the following code is more readable when I use property.

string agency = base.GetAgencyDetails();

string agency = base.Agency; //I could write same logic in getter of the property.
like image 413
deen Avatar asked Dec 03 '25 05:12

deen


1 Answers

Personally, I'd follow the MSDN Guidelines on this.

In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

It makes perfect sense if you think about it, a method would be more suited to something that would potentially alter data in some way, and a property is perfect for when you're retrieving some data and caching it.

If you're using an explicitly backed property, you could even combine the two in the case of a transform:

private ObjType _myObjWithStringification;
private string _stringRepOfData;

public string StringRepresentation
{
    get {
        if (_stringRepOfData == null) {
            _stringRepOfData = _myObjWithStringification.ToString();
        }
        return _stringRepOfData;
    }
}

Re: Your maintainability comment, I'm not sure it's very much valid. If you were to hit F12 to go to the declaration of the property you're using, you'll go straight to the getter anyway, just like you'd go to the method body if you used a method.

I'm not sure it's safe to assume that a property isn't going to have any custom retrieval logic.

like image 150
Rudi Visser Avatar answered Dec 04 '25 20:12

Rudi Visser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!