473,624 Members | 2,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Properties question

LDD
What is the real benefit of using Properties?
You can declare class variables either public/private.

I'm not sure I understand the true benefit. Especially if you are reading
from/writing to these variables
Nov 23 '05 #1
11 1227
Properties have the benefit of accessors. You have a getter and a setter
where you can put some additional logic, like raising an event to notify
subscribers that a property changed, ....

Gabriel Lozano-Morán

"LDD" <la************ ***@gmail.com> wrote in message
news:fv******** ************@ma gma.ca...
What is the real benefit of using Properties?
You can declare class variables either public/private.

I'm not sure I understand the true benefit. Especially if you are reading
from/writing to these variables

Nov 23 '05 #2
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}

Nov 23 '05 #3
Another reason might be to validate the data. For instance, suppose you
have a property that is an integer, but you only accept values in a certain
range. Well, before you set your private variable, you can check the value
and, maybe, throw an exception if the value is incorrect.

<mi************ @gmail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}

Nov 23 '05 #4
Even more, when thinking about derived classes, you cannot override the
behaviour of fields, but you can using properties. It's totally clear that a
code like the following seems to add an extra overhead when you first look
at it:

class A {
Guid id;

public Guid Id {
get {
return id;
}

set {
id = value;
}
}

If you will never change that implementation and you will never derive from
that class, well, then you may use

class A {
public Guid id;
}

But, as already said in the previous postings, if you need to check the
field content or raise events or start a thread or whatever else you may
think of when the field changes, the only way is to use a property. The most
simple example for it is a class having some fields and you want to know if
an instance of this class is dirty, meaning that one ore more properties
were modified. Using fields instead of properties, you would certainly end
up using code like the following:

class A {
public Guid Id;
public string Name;
public decimal Price;

public Guid old_Id;
public string old_Name;
public decimal old_Price;

public bool IsDirty {
get {
return (old_ID != Id && Name != old_Name && Price != old_Price);
}
}
}

If you have a class with 20 or more properties, IsDirty will become slow and
you will likely forget to add new comparisons to it when adding new fields
to the class. Furthermore you have to store two values for each field to be
able to evaluate if the instance was modified.

Compare this solution to the follwing:

class A {
public Guid id;
public string name;
public decimal price;
public bool isDirty;
public Guid Id {
get {
return id;
}

set {
if (id != value) {
id = value;
isDirty = true;
}
}

public string Name {
get {
return name;
}

set {
if (name != value) {
name = value;
isDirty = true;
}
}

public decimal Price {
get {
return price;
}

set {
if (price != value) {
price = value;
isDirty = true;
}
}

public bool IsDirty {
get {
return isDirty;
}
}
}
As you can see, there is no need to store the original values to find out if
an instance has changed. Now let's say that the price must be positive, as
you usually have to pay for everything that you can buy. If you find someone
giving you money when you buy some items, please let me know. How do you
check that with public fields? You can't. Well, you could if you have a Save
method or something similar, that checks for valid values, but the problem
is that you never know the piece of code that actually stored the invalid
value. You will only know about it when you call the Save method, which
makes finding errors a lot harder. A much better approach is the follwing:

public decimal Price {
get {
return price;
}

set {
if (price <= 0) {
throw new ArgumentExcepti on("Price must be a positive
number.");
}

if (price != value) {
price = value;
isDirty = true;
}
}
Yeah, throw an exception. Exceptions are your friend not the evil :-)

Last example: You have a class B deriving from class A and you don't want to
allow the price to be lower than 20. Can you do this check with public
fields? No, you can't. But you can with properties. Simply add the virtual
keyword to the Price property in class A:

public virtual decimal Price {
...
}

and in class B do the following:

class B : A {

public override decimal Price {
get {
return base.Price;
}

set {
if (price <= 20) {
throw new ArgumentExcepti on("Price must be at least 20
bucks.");
}

base.Price = value;
}
}
Whatever code you have implemented in class A will be executed through the
base.Price calls but you're also able to extend the logic (in this case the
comparsion >= 20).
If you still want to use public fields, go for it. Noone will stop you from
doing it and if you're very careful your application will work. However,
properties will help you in structuring your code and allow to write code at
exactly the place where it belongs. Ok, you need to add a few lines to add
the accessors, but it's worth it.

Need a last example? Try to implement a read-only field :-)
Michael
"Peter Rilling" <pe***@nospam.r illing.net> schrieb im Newsbeitrag
news:ue******** ******@tk2msftn gp13.phx.gbl...
Another reason might be to validate the data. For instance, suppose you
have a property that is an integer, but you only accept values in a
certain range. Well, before you set your private variable, you can check
the value and, maybe, throw an exception if the value is incorrect.

<mi************ @gmail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}


Nov 23 '05 #5
Michael Höhne <mi************ @nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you from
doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #6
LDD
Thanks for the info folks.
I didn't understand why you would use properties if you could just declare
the vars as public.

My focus was on the wrong idea...

thanks again

LDD

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Michael Höhne <mi************ @nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you from doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #7
>> Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."
public readonly int x = 10;

Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.

Michael

"Jon Skeet [C# MVP]" <sk***@pobox.co m> schrieb im Newsbeitrag
news:MP******** *************** *@msnews.micros oft.com...
Michael Höhne <mi************ @nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you
from
doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #8
Michael Höhne <mi************ @nospam.nospam> wrote:
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."


:)
public readonly int x = 10;


Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.


It's a const whose "constant value" may decided at initialisation time,
rather than the normal const which is "baked in" to any code using it.

I was really just being picky though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #9
>>I was really just being picky though :)
I know :-)

"Jon Skeet [C# MVP]" <sk***@pobox.co m> schrieb im Newsbeitrag
news:MP******** *************** *@msnews.micros oft.com...
Michael Höhne <mi************ @nospam.nospam> wrote:
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I
have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."


:)
public readonly int x = 10;


Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.


It's a const whose "constant value" may decided at initialisation time,
rather than the normal const which is "baked in" to any code using it.

I was really just being picky though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 24 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7507
by: Lyn | last post by:
Hi, This question may seem a bit academic... To learn more about Access VBA, I have been enumerating the properties of various form controls. This was mostly successful and I have learned a lot from the process. It occurred to me that I could also enumerate the properties of the ADO Recordset in similar fashion, expecting to get back known properties such as AbsolutePosition, BOF, EOF, Filter, Sort, etc. I inserted the following
3
3313
by: cwertman | last post by:
I have a question regarding dynamic properties. I have an Object say Account --Id --Prefix --Fname --Lname --Suffix
47
467
by: Jon Slaughter | last post by:
private string name; public string Name { get { return name; } set { name = value; } } In the above, why doesn't C# just allow one to create a single directive to make a property?
39
1930
by: Paul Mcilreavy | last post by:
Hi, i would like to get some view points on the use of properties within classes. My belief is that properties should generally be used to return values of private members. They should not do anything that is likely to return an error and they should not instantiate or return any big objects etc. My company seems to be using them for everything which is starting to cause me concern. Any comments or other viewpoints is appreciated.
4
5723
by: beatdream | last post by:
I am designing a database to handle different kinds of products ... and these products can have different properties...for example, a trouser can be specified by the width, length, color, and other additional properties...while you might need only one property for another product, e.g litres for a soft drink...so I was thinking of creating a properties table, a units table and a product table, properties-unit table... and...
0
8246
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8179
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8685
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8490
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6112
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4184
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.