On properties and their usage

  • Thread starter Thread starter Gary Morris
  • Start date Start date
G

Gary Morris

Hello all,

OK, first of all I have known about properties since VB6, which
I have and have used extensively. It seems that property get
and set are basically the same concept in C# and VB.NET, so
no problem there. In programming with VB6, I never wrote any
program that used properties, and to date I still haven't ever
used them in C#. What I really want to know is, when should I
use them at all? I mean, we have variables (now referred to as
fields, I think), which can be made public or private, but all the
time I see code which:

- first declares a field as private
- then uses a public property to read or write to the private field

Now, I can understand how they would be really handy when
you need a read-only field, but for the life of me I cannot see the
point in creating yet another member for a class that does
nothing except assign/read a value to/from a private field that
could have just been made public to begin with. I also want to
state that I can see a good use for them if you wanted to DO
something to the field after it's read or written, and that's the
only use I can see for properties. After all, a public field is
accessed from code outside it's containing class just like a
property is, so why bother with something like:

private int MyInt;

public int MyIntP
{
get
{
return MyInt;
}
set
{
MyInt = value;
}
}

Now, if the set part went like this:
......
set
{
MyInt = value * 2;
}
......
I could understand that with no problem.

It just seems to me that it does exactly the same thing as a normal
public field does. I would like to hear an explanation as to why this
is used so often when the property does nothing to the private field
except to read/write its value. If I'm missing something really
important here, I want to know about it, but if not, I also want to
know why so many people use them (constantly) if there is not a
legitimate need.

Thanks.
 
Gary Morris said:
Hello all,

OK, first of all I have known about properties since VB6, which
I have and have used extensively. It seems that property get
and set are basically the same concept in C# and VB.NET, so
no problem there. In programming with VB6, I never wrote any
program that used properties, and to date I still haven't ever
used them in C#. What I really want to know is, when should I
use them at all? I mean, we have variables (now referred to as
fields, I think), which can be made public or private, but all the
time I see code which:

- first declares a field as private
- then uses a public property to read or write to the private field

Now, I can understand how they would be really handy when
you need a read-only field, but for the life of me I cannot see the
point in creating yet another member for a class that does
nothing except assign/read a value to/from a private field that
could have just been made public to begin with. I also want to
state that I can see a good use for them if you wanted to DO
something to the field after it's read or written, and that's the
only use I can see for properties. After all, a public field is
accessed from code outside it's containing class just like a
property is, so why bother with something like:

private int MyInt;

public int MyIntP
{
get
{
return MyInt;
}
set
{
MyInt = value;
}
}

Now, if the set part went like this:
.....
set
{
MyInt = value * 2;
}
.....
I could understand that with no problem.

It just seems to me that it does exactly the same thing as a normal
public field does. I would like to hear an explanation as to why this
is used so often when the property does nothing to the private field
except to read/write its value. If I'm missing something really
important here, I want to know about it, but if not, I also want to
know why so many people use them (constantly) if there is not a
legitimate need.

This is a fairly common question, and basically, its done simply because its
good practice and provides consistency. By always using properties, every
class always uses properties, and its easier to understand. I personally
write *way* more read only properties than read\write, so to provide a
consistent interface I use properties when I do write a read\write property.
Of course using properties also means you can also put in validation code,
events, etc on the set handler, change the backing storage, be virtual and
otherwise decouple client code from the internals of your class.

However, I only follow those rules nessecerily on public and protected
members. For internal members you are free to use whatever you want, using
properties where you may be concerned with something and fields for simple
classes. I however always write either strictly properties or strictly
fields in a given class, again to retain consistency(problem with fields
here is if I change one to a property I usually change all others to
properties too).
 
Gary,
In addition to Daniel's comments.

IMHO it is better to make your fields Private and use Properties as it
promotes encapsulation.

Remember Encapsulation is one of the top 3 tenants of OOP. The other 2 being
Inheritance and Polymorphism.

Properties are .NET method of encapsulating field or attribute data.

Also some classes in the Framework play nicely with properties while they
totally ignore public fields. Such as the System.Windows.Forms.PropertyGrid
and Data Binding.

Hope this helps
Jay
 
Why do folks do it? A good question.

There is no problem with refactoring an existing class to add in the
property getter and setter. In fact, you can inherit from a class that has
non-hidden properties and create a hidden property with the same name,
without breaking the interface.

For example, let's say you have

class MyClass
{
public int MyValue1 = 0;
}

// and then declare a child class

class MyChildClass : MyClass
{
private int _MyValue1 = 0;
public new int MyValue1
{
get { return _MyValue1 * 2; }
set { _MyValue1 = value * 2; }
}
}

This works just fine. The new property getter and setter hides the original
property.

So why create the property getter and setter from the outset?

I have no earthly idea, except some purists seem to feel that it is more in
keeping with the goals of object oriented design. That said, I admit to
doing this myself, out of a sense of "why not" and "others say this is a
good thing to do."

I know this doesn't help... I'm just agreeing with you :-) I'm looking
forward to other responses.

--- Nick
 
An OO Purist wont use C#; its not what I would call a pure OO suitable
language.

As for properties, you cant throw an exception on a field if its outside a
specified range, or you cant fire an event if it changes. You can with
properties.
 
One thing I dont like about C# properties is that you cannot pass them ref
into methods and treat them like fields as theyre basically "appearing" to
be fields but in reality theyre not.
 
Nick Malik said:
Why do folks do it? A good question.

There is no problem with refactoring an existing class to add in the
property getter and setter.

Well, you can do that if you've got all the sources to all the code
which uses your class. Very often that's not the case.

Using properties gives you room to change things later on without
breaking the client interface. You could decide to not use a field but
access the data from a database, or to use a single field for more than
one property - all without changing any existing code. You can't do
that using a straight field: even if the code could be recompiled to
use the new property name (which would violate naming conventions to
start with, if the field name hadn't), that wouldn't help libraries
which people don't have the source to but which want to target your
code. (Yes, they could target an old version of your code, but they may
not want to.)

Basically, breaking interface compatibility is a bad thing - using
properties avoids the need for it in many cases where using fields
doesn't.
 
One thing I dont like about C# properties is that you cannot pass them ref
into methods and treat them like fields as theyre basically "appearing" to
be fields but in reality theyre not.
There is good reason for that, it wouldn't work. A pass by reference
variable references the original variable reference, properties *return* a
reference, the ref variable would update the *returned* value and not change
the property. Allowing that to work would also defeat readonly(or get only)
properties.

This however does offer an argument for properties vs fields. In this case
changing fields to a property is a potential *source* breaking change,
instead of the binary breaking change they are often advertised as.
 
Allright!

I cannot believe, first of all, that this post got so many
replies in the first few hours, though I figured there
would be many.

Second, I'm glad that there were so many because it
helped me to understand the practice a little better. I
used "straight" programming since the beginning of
BASIC, and I've seen more than my share of the classic
"spaghetti code" programs. Now, in my experience, a
lot of the early programmers would have embraced OO
programming with open arms, and, in fact, I have seen
some really good attempts at trying to manage code
even using the old GWBASIC. Right now, I am still trying
my best to get used to the OO concept, and I think I am
doing fairly well so far. I started small and am working
my way up, but I think what prompted me to ask this
was seeing so many small apps that used properties like
they were mandatory and going out of style or
something!

I picked up .NET about a year ago, and have been totally
fascinated with it ever since. VB.NET struck me as a
feeble attempt to bring the language to a new level, and,
even though I started with BASIC and ended up with VB6,
I just couldn't deal with it. The way I saw it, it's just as
easy to learn a new language (C#), as to learn a new VB.
The ONLY thing I don't like about .NET is the fact that
there is literally so much to learn, and after a year I still
haven't gotten more than about 25% or so. The classes
provided are astounding. I have written countless routines
only to find out later that "there's already a way to do that
with the <whatever> class".

You guys have been great, and I appreciate the timely and
detailed responses. Properties will be one of the things I
will concentrate on, and I'll TRY to make it a regular
practice from now on (I won't get obsessive about it
though). I seriously hope that there will be even more
responses to this, as I am anxious to hear more opinions as
well as facts about it.

Thanks again guys, and I hope you are all well!
 
I just thought I would chime in while we were on the subject.

One thing I originally worried about was performance of properties versus
fields. To me, that would be the only reason to decide to use a public
field instead of a private field and public property.

In VB6, using Property accessors did hurt performance a bit. Due to the
nature of COM, the Get/Let/Set accessors would always be called as
functions.

Thankfully, in .NET, the JIT compiler will almost always inline a property
accessor so that the executed code just accesses the field directly anyway.
That is unless your Get or Set procedure has lots of logic which makes the
attached function too large for the JIT to want to inline it. In that case
there probably wouldn't be an advantage to inlining the property anyway.
Actually, if your Get is complicated enough that it may take a while to
perform, best practices dictate you use a method anyway.

In practice, I've noticed that a Property Set with a validation check, an
event trigger, and a field setter should still be small enough to be
considered for inlining. Since this is the case, you may even want to use
these Public Properties inside the class itself, instead of the fields
directly (unless for some reason you want to set a value without triggering
an event or validating, which is sometimes a requirement).

As others have mentioned, one particularly useful use of Property accessors
is the ability to change how the data is stored on the class without
breaking the public interface. For example, I will often times have a class
with one or two Boolean properties, which I will store as two separate
Boolean fields for simplicity. Later on, if I find I have about 20 Boolean
properties, I can change these to be stored with a Flags enumeration that
can fit in an Int32, and use bitwise operations in my Get/Set accessors.
The class goes from taking 20 bytes for all the booleans to 4 bytes, without
breaking the public interface.

This is a simple example that shows an extreme case of what you can do, but
I assure you it happened to me.

--Matthew W. Jackson
 
If you look at WinForms events, you see things like SizeChanged and
LocationChanged, these events could not be fired if it wasnt for
properties. Properties are methods in disguise with convience of field
access (except passed as a ref parameter into a method call).
 
An OO Purist wont use C#; its not what I would call a pure OO suitable
language.

Just curious, what does C# lack which would otherwise make it a pure
OO language?

<snip>
 
Just curious.

Should a pure OO language be type based? Should it allow static objects?
Multiple inheritance?
 
Yes, an OO language should allow Singleton Classes ("static objects" ) which
C#/Framework does.

Yes, an OO language has to be Type based but be able to pass all Types
around as a base of the types which C#/Framework does. For example,
retuning an Int32 as an object.

IMHO, Multi Inheritance is not necessary. Single Inheritance with Multi
Interface Inheritance, which C#/Framework supports, is OO enough to satisfy
all the common design patterns.

All comments are welcome.
 
Gary Morris said:
And, if I might ask, just which language (if any) IS a pure OO
suiitable language?

In my experience, SmallTalkers often cite SmallTalk as the *only* pure
OO language - or at the very least, significantly more pure than Java
and C#. There may be other "pure" OO languages around now, but
SmallTalk is likely to be the best known.
 
Back
Top