?
Solved

Why use properties?

Posted on 2006-05-08
21
Medium Priority
?
368 Views
Last Modified: 2010-04-16
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
0
Comment
Question by:paulwhelan
  • 5
  • 4
  • 4
  • +5
21 Comments
 
LVL 10

Expert Comment

by:_Katka_
ID: 16628995
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
0
 
LVL 5

Expert Comment

by:pgloor
ID: 16629207
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
0
 

Author Comment

by:paulwhelan
ID: 16629270
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
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16629314
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.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 16629337
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.
0
 
LVL 9

Expert Comment

by:WinterMuteUK
ID: 16629477
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.
0
 
LVL 9

Expert Comment

by:jonorossi
ID: 16629839
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.
0
 

Author Comment

by:paulwhelan
ID: 16630388
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
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16630450
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.
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 120 total points
ID: 16630494
Essentially you could validate the data in anyway you wanted to in the property. A more sensible example might be a Person class with an age:

    class Person
    {
        int _age;

        public int Age
        {
             get { return _age; }        
             set
             {
                  if (value < 1 || value > 100)
                      _age = 10;
                  else
                      _age = value;
             }
        }
    }

By using a property for the age we can validate that it is greater than 0 and that it is less than 100 (a resonable upper age limit). We wouldn't be able to do this if we simply used a public int field.
0
 
LVL 9

Expert Comment

by:jonorossi
ID: 16630611
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.
0
 
LVL 9

Expert Comment

by:WinterMuteUK
ID: 16630836
Jon:

"Just one more thing.

Why not just make private fields public?"

Wint.
0
 
LVL 9

Expert Comment

by:jonorossi
ID: 16630968
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
0
 

Author Comment

by:paulwhelan
ID: 16631063
Thanks carl

One last question, why the underscore in _age?

thanks
Paul
0
 
LVL 9

Expert Comment

by:jonorossi
ID: 16631105
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.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16631107
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.
0
 
LVL 9

Expert Comment

by:WinterMuteUK
ID: 16632006
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.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16633830
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.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16633859
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.
0
 
LVL 9

Expert Comment

by:jonorossi
ID: 16635544
Sorry WinterMuteUK, I must have missed that one with so many replies.
0
 
LVL 9

Expert Comment

by:WinterMuteUK
ID: 16637210
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.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question