Link to home
Start Free TrialLog in
Avatar of paulwhelan
paulwhelan

asked on

Why use properties?

Hi

Why should I use Properties?

I mean is a Property like this

public int Size
        {
            get { return _iSize; }
            set { _iSize = value; }
        }

just the same as two methods

getSize();
setSize(int value);

Thanks
Paul
Avatar of _Katka_
_Katka_
Flag of Czechia image

Hi, you're right in some cases it's just the same.. But:

1) only properties are visible within PropertyGrid (if wanted) when designing component (and descedants)
2) you can determine by GetType().GetProperties which ones are properties and which are Methods (also needed sometimes) consider this:

  Person [class]
     Weight [property]
     Height [property]
     UpdateBMI(); [method]
 
now you can automatically suck the information about Person (it's properties) -> Weight, Height and ignore the UpdateBMI because it's just a supporting method
in your case:

  Person [class]
    GetWeight [method]
    GetHeight [method]
    UpdateBMI(); [method]

you can't determine which one's are properties and which are just supporting methods

3) it's slightly shorter because it's supported by IDE

regards,
Kate
Avatar of pgloor
pgloor

Besides all theories about encapsulation and reflection, I like to think in objects. I mean thinking about them like abstract models from the real world.

Objects always have:
- Properties
- Methods
- Events

Following this simple rules I have a consistent model and I always know where to look for something and I dont have to search around for GetThis() and SetThat(whateveritis) functions.

And since I'm lazy, I have to write lesser code, or at least I think its better readable.

Peter
Avatar of paulwhelan

ASKER

Thanks for that.

Just one more thing.

Why not just make private fields public?

Would that not mean I can assign the value that way?

Person Paul = new Person();
Paul.Weight = 100; //if the private field is changed to public?

Thanks
Paul
Essentially one of the benefits of using properties is that you "hide" the implementation. Weight might be an int now, but what if you decided to change its data-type in the future ? Anyone who used your object would need to change their code to match. Or, what if somebody tried to set weight to a negative value ? a negative would be ok for the data-type, but probably not what you intended to be stored in it. So, properties allow you to validate the values that are stored in them.
One reason is it is easier to debug properties than it is for fields.  If you had a bug where Person.Weight was being set to the wrong value, but you did not know how that was happening, you could just set a breakpoint on the Weight Set property method and then run your code(or just put debug statements there).  If it is a field, then you COULD set a global breakpoint on valuechange, but that effects the performance of your application.

Another reason, is that it better supports encapsulation.  Suppose you wanted to store the Weight as a double.  If you changed the public field type, then you would have to recompile EVERYTHING that touches the field.  As a property, you could just keep the int Weight and add another property to set the double weight(ExactWeight);  both properties would set the same internal field.
With a property you have the ability to only supply setters or getters. For example you might have the 'Weight' bit as:

   public double Weight { get { return weight; } }

with this people can only read the property, they can't change it.
With .NET 2.0 you can have public and protected getters/setters:

  public double Weight
  {
    get { return weight; }
    protected set { weight = value; }
  }

this allows you to use the setter in your code, but only supply the getter to the public.

So, in short another reason is to prevent access to your member variables, or to provide read/write only access.

Another, another reason is that you can have bits of code in the 'setter' (or indeed the getter, though less common), for example, lets say 'BMI' is a property, and our Person class looks like this:

   public Person
   {
      Weight { get; set; }
      Height { get; set; }
      BMI { get; }
   }

We can have BMI defined either as:
   public double BMI { get { return Weight * Height * WhateverTheHellItIs; } }

or
   public double BMI { get { return bmi; } }

if BMI is getting called a lot, then the first definition would cause a performance hit, as we'd be calculating the value every time, even though the Weight/Height values haven't changed. BMI only changes when Weight and Height change, so we could calculate the BMI in their setters:

  public double Weight
  {
    get { return weight; }
    set
    {
       weight = value;
       bmi = Weight * Height * WhateverTheHellItIs;
    }
  }

This way we only set bmi when it's value changes.

Wint.
As someone started to talk about properties are designed to be attributes of the domain object, while methods are action performed on it.

Example:
An employee has a name: employee.Name = "John"
An employee has a date of birth: employee.Dob
You can promote an employee (this would change thier position and internally calculate their new salary and change it): employee.Promote(Position.ProjectManager)
You can fire an employee (which would set values to ensure they weren't paid any more): employee.Fire()

As you can see properties fit better to attributes of the object, while methods tell the object to perform an action on itself.

I hope that gives you a better idea of why C#/.NET has properties. I think I remember hearing that Java now has properties but I maybe wrong.
Carl

"Essentially one of the benefits of using properties is that you "hide" the implementation. Weight might be an int now, but what if you decided to change its data-type in the future ? Anyone who used your object would need to change their code to match. Or, what if somebody tried to set weight to a negative value ? a negative would be ok for the data-type, but probably not what you intended to be stored in it. So, properties allow you to validate the values that are stored in them."

Would that imply that you need to check if the value passed to the property is of the correct type?

i.e if Weight was an int and then it was changed to a double - would we need to check the value coming in was a double? Or that it wasn't negative? (as it could have been with the int).

Thanks
Paul
You would need to check for negative if you didn't want it to be able to store negative. You could change to double without any problems because int can be implicitly converted to double by the CLR. But the point is that if you use properties then you are free to alter how the data behind the property is stored without changing the way that programs interact with your object.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Everyone isn't reading Paul's question properly. He is asking why should he use properties instead of accessors and mutators. They both achieve the same thing, actually if you load a .NET assembly into reflector properties are named like set_Name and get_Name, but this is all done but the compiler so you don't have to worry about it. You can do validation/error checking with both properties and accessors (get) and mutators (set). Paul is not asking why not just make my member variables public.
Jon:

"Just one more thing.

Why not just make private fields public?"

Wint.
Wint: Firstly anyone who uses the class will see that they are fields and not properties or methods, VS shows this. The main reason is that you have no way to check that the data changes is valid. It might be simple to give give access to the string, but if it is an ArrayList or similar the user of the class has to directly access the internal data stuctures of the class when is against the OOP of encapsulation; it also doesn't allow you to change any of the internals of how the class works. If you learn about Abstract Data Types (ADTs) you will understand why very easily, just do a google search and read an intro. ADTs are classes like ArrayList; if you were able to access the variables inside the ArrayList Microsoft would never be able to make any changes or fix any bugs with it because you so heavily relie on the way it currently is; this is why encapsulation is very important.

Hope that helps, Jono
Thanks carl

One last question, why the underscore in _age?

thanks
Paul
Most people prefix their class level variables with something:

_age
m_age
iAge
intAge
etc

I like to use the _age style because it helps in recongising what variables are local and which are not. It also allows you to name parameters with the same name (age) without having to use this.
Just one of a number of possible naming convensions for member variables. The advantage of prefixing them with _ is that they'll always appear grouped together in the IntelliSense window and they'll appear first in the list.
Jono,

I wasn't after an explanation, I was merely responding to your point:
  "Paul is not asking why not just make my member variables public"

By pointing out he actually had (please see the post on 05/08/2006 10:48AM BST), which did ask that, nothing else.

Cheers though

Wint.
one more thing why you should a property instead of a function:
if your property code is short, it can be inlined by the compiler which means faster runtime.
and one more comment to boxing datatypes like int to value, i would not recommend that because of too much overhead in the opcode for that.
Sorry WinterMuteUK, I must have missed that one with so many replies.
It's no worries jono, just thought I'd point it out, I didn't do it in a very good way though...
Sorry for not being clearer!

Wint.