Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Properties and Methods?

I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?

like image 329
Dr. Watson Avatar asked Jul 30 '09 21:07

Dr. Watson


People also ask

When should you use properties?

Consider using a property if the member represents a logical attribute of the type. Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

What is the difference between methods and properties?

Properties define the characteristics of an object such as Size, Color etc. or sometimes the way in which it behaves. A method is an action that can be performed on objects. For example, a dog is an object. Its properties might include long white hair, blue eyes, 3 pounds weight etc.

What is the difference between properties and methods in Python?

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.

What is the purpose of properties?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.


1 Answers

It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.

Use it because of convention, and that it looks nicer.

Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.

like image 59
Dykam Avatar answered Oct 31 '22 19:10

Dykam