473,804 Members | 3,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why are get/set properties useful?

VMI
WHy are the get/set properties so useful? I know they're used so that I don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.
Apr 20 '06 #1
21 23991
By using the properties, as opposed to making the variables they access
public, you can control what data goes into them, and how the data is
returned. For example, on the set property, you can validate the data and
return an error if it isn't valid. So if you have a State property on an
address object, you can make sure that it's one of 51 valid entries. Or you
can make sure a string will fit into a database field before you allow it to
be stuck into the field, so you always know the object is valid.

I haven't found as much use for the get property, but you can use it for the
same sort of things. You can also use JUST a get property to make a
read-only property (so once the object is loaded with data from the
contructor or a "fill" function, external applications and objects can only
read the values).

Anyway, there you go. My $0.02.

Clint

"VMI" <VM*@discussion s.microsoft.com > wrote in message
news:4C******** *************** ***********@mic rosoft.com...
WHy are the get/set properties so useful? I know they're used so that I
don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.

Apr 20 '06 #2

VMI wrote:
WHy are the get/set properties so useful? I know they're used so that I don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.


Lots of reasons, but the biggest one is control and conversion.

Control:
Let's assume that for some reason, my value can only be from 1-10.
If I allow the user to assign a value outside that range, my program
may
crash or do weird things. If the setter does not allow a value outside
the
range 1-10, I don't have this problem. Likewise, let's say that I want
to
change some OTHER variable when you set one of the values. I can do
that in the setter. Finally, suppose that I don't want to do things if
the
value you give me is the same as the current value. I can do that in a
setter.

Conversion:
If I have a set routine that takes a value of another type, such as a
string
instead of an integer, I can convert it to whatever I want without the
user
being aware of what my internal representation is.

Matt

Apr 20 '06 #3
Smells of homework, but...

Starters for 10:

* In the accessors (get/set) you might want to apply locking to prevent 2
threads monkeying with the value at once
* In the accessors you might want to validate the new value; check it is
legal and throw an exception if not (and yes: exceptions from setters IS
reasonable; the framework does it often enough; sometimes the getter might
throw if it is not reasonable to ask this)
* The setter (or more rarely, getter) may have local consequences beyond the
constraints of that field; arguably should be exposed via a method, but does
happen
* The setter might want to notify other code that a change has occurred via
notification events
* The value might be lazy-loaded, so not known until queried (e.g. still in
the db)
* The value might be dynamically calculated (think .Count)
* Isolates implementation from interface
* Might want different access; read only (.Count), write only (.Password),
or different access on the getter and setter (possible in 2.0)
* For value-types, the difference is more pronounced; a getter will return a
*clone* of the value; hence .SomeStructProp erty.SomeMethod () and
..SomeStructFie ld.SomeMethod() are very different; the property one works on
a different object, the field works on the same

Marc
Apr 20 '06 #4
VMI
Thanks for the info. And it's not for homework LOL It's just that I've seen
it alot and just didn't fully understand it.
I had a vague idea that it might be for data control, but all the examples
I've seen didn't make much sense. In this example (comes from a tutorial)
it's being used without much purpose:

class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}

"VMI" wrote:
WHy are the get/set properties so useful? I know they're used so that I don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.

Apr 20 '06 #5
A fundamental principle of object orientation is encapsulation.

An object should have full control over it's data at all times.

The get-set accessor enables an object to ensure that it must do some
intelligent processing when an external object tries to update it's data.

Exposing public variables is a huge no-no because an external object can
change the state of the variable without the owning obects knowledge. This
is a recipie for disaster.

There is no good excuse for public variables in a well designed
object-oriented architecture.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"VMI" <VM*@discussion s.microsoft.com > wrote in message
news:4C******** *************** ***********@mic rosoft.com...
WHy are the get/set properties so useful? I know they're used so that I
don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.

Apr 20 '06 #6
> I haven't found as much use for the get property, but you can use it for
the same sort of things. You can also use JUST a get property to make a
read-only property (so once the object is loaded with data from the
contructor or a "fill" function, external applications and objects can
only read the values).
Here's one. In the following example, class a contains an instance of class
b, but doesn't want to expose all of it to the client. So, it uses public
properties to expose those properties of b as it wants to:

public class a
{
private class b;

public int c
{
get { return b.c; }
}

public a()
{ b = new b(); }
}

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Clint" <no****@nowhere .non> wrote in message
news:uu******** ******@TK2MSFTN GP03.phx.gbl... By using the properties, as opposed to making the variables they access
public, you can control what data goes into them, and how the data is
returned. For example, on the set property, you can validate the data and
return an error if it isn't valid. So if you have a State property on an
address object, you can make sure that it's one of 51 valid entries. Or
you can make sure a string will fit into a database field before you allow
it to be stuck into the field, so you always know the object is valid.

I haven't found as much use for the get property, but you can use it for
the same sort of things. You can also use JUST a get property to make a
read-only property (so once the object is loaded with data from the
contructor or a "fill" function, external applications and objects can
only read the values).

Anyway, there you go. My $0.02.

Clint

"VMI" <VM*@discussion s.microsoft.com > wrote in message
news:4C******** *************** ***********@mic rosoft.com...
WHy are the get/set properties so useful? I know they're used so that I
don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.


Apr 20 '06 #7
"There is no good excuse for public variables in a well designed
object-oriented architecture."
That's a fairly bold statement...Par ticularly when you can't send a
property by reference to a function. In an SAP application I
maintained, I saw a class that contained public variables so they could
be passed byref to the SAP connector and be filled/instantiated by its
code. I know it could have been done in another way, but I thought
using public fields was at least not completely insane in this
instance.

-Jared

Apr 21 '06 #8
Like any other rules, this sort of rule is based upon the underlying
principle. It is better to understand the underlying principle than to
simply adhere to a set of rules. The rules will, as you've observed, have
exceptions, while the underlying principles have none. In addition, it is an
easy trap to get caught up in the complexity and sheer number of rules which
may be derived from a principle, which, due to the number of rules,
exceptions and special cases, are much harder to keep track of than basic
underlying, unchanging principles.

When someone tells you a rule, it is often a good idea to ask them to
explain the underlying principle behind it. If they cannot, the rule is more
likely to be unreliable.

Note that I am not saying that the rule in question is not generally true.
It is. I am merely making a point in principle about the usefulness of
relying upon rules rather than principles.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"JaredHite1 " <ja***@sharingd s.org> wrote in message
news:11******** **************@ e56g2000cwe.goo glegroups.com.. .
"There is no good excuse for public variables in a well designed
object-oriented architecture."
That's a fairly bold statement...Par ticularly when you can't send a
property by reference to a function. In an SAP application I
maintained, I saw a class that contained public variables so they could
be passed byref to the SAP connector and be filled/instantiated by its
code. I know it could have been done in another way, but I thought
using public fields was at least not completely insane in this
instance.

-Jared

Apr 21 '06 #9
Here's one that might make more sense. It's just a simple example:

public class Circle
{
private float centerPoint;
private float radius;

public float Diameter
{
get { return radius * 2.0; }
}

public float Circumference
{
get { return 2.0 * Math.Pi * radius; }
}

public void Draw Circle()
{
//Draw circle to some object
}

public float Radius
{
get { return radius; }
set {
if( value > 0.0)
{
radius = value;
DrawCircle();
}
else
{
throw new Exception ("Invalid radius.");
}
}
}

"VMI" wrote:
Thanks for the info. And it's not for homework LOL It's just that I've seen
it alot and just didn't fully understand it.
I had a vague idea that it might be for data control, but all the examples
I've seen didn't make much sense. In this example (comes from a tutorial)
it's being used without much purpose:

class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}

"VMI" wrote:
WHy are the get/set properties so useful? I know they're used so that I don't
directly access a variable, but why is that so useful? What would the
difference be between using it directly and using get/set?

Thanks.

Apr 21 '06 #10

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

Similar topics

24
5451
by: downwitch | last post by:
Hi, I know this has been covered here and in the .public groups, but it seems like it's been a while, especially around here, so I just thought I'd ask again to see if anyone has figured out a new angle. If I have a class MyClass--not a collection container but a single-level class--that has a bunch of properties of different types, I'd like to be able to reference them via the standard VBA syntax of
23
391
by: Marcin Grzêbski | last post by:
I red MSDN article of C# 2.0 this week... and i found very strange syntax for properties e.g.: public int MyIntValue { get { // ... } protected set { // ... }
20
8348
by: Ben R. | last post by:
I see tons of examples where people use properties where the get and set correspond directly to a single variable in a class. If this is the case, why not just access the variable directly? Is it an encapsulation issue? This seems strange since there's often no restriction applied at the level of the property. Just curoius... -Ben
11
2555
by: Brent Ritchie | last post by:
Hello all, I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. As well as learning C#, I think that it's way overdue for me to start learning C++ Templates (I've been learning it for about 5 years now). I think that adding this type of functionality would be a good exercise to help learn template programming....
3
3345
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?
17
2789
by: David C. Ullrich | last post by:
Having a hard time phrasing this in the form of a question... The other day I saw a thread where someone asked about overrideable properties and nobody offered the advice that properties are Bad. So maybe we've got over that. I suppose properties could have Bad consequences if a user doesn't know they exist and think that a certain property of an object is just an ordinary attribute. But that applies to
26
2857
by: Max2006 | last post by:
Hi, C# 3.0 extension methods become useful for us. Do we have the similar concept for extension properties? Thank you, Max
26
1787
by: optimistx | last post by:
A variable in global scope var a1 = 'contents of global variable a1'; can be references (with some limitations) as window; // or window.a1; // or even window;
0
9706
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
9579
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
10578
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
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10077
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
9152
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
7620
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...
1
4300
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
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.