Re: fields or properties



Well, lets see. I think maybe you are confused about the difference between
them as they are very different things. The easiest way to answer this
would be with an example I guess.

When you write a class you more times than not need variables to hold data
in order for the class to operate correctly. These variables that are
defined in the class are known as fields. They are really nothing more than
variables defined in the class to hold data in order for the class to work
its magic.

However, there is a major problem with exposing these variables(fields) to
the user of the class. Just because you are writing the class and
understand how its suppose to work, doesn't mean the guy next year that
creates an instance of your class will understand all the inner workings of
it.

So when you lay out your class and one of the fields named "CustPhone" needs
to always be formatted like: 111-111-1111, you can't be sure the guy using
your class or even you will remember that later on.

In comes properties. Properties are really not variables at all, but are
rather functions that handle writing and reading from your internal
variables or fields. By using the Set and Get features of properties you
are now able to control what gets written to and read from your internal
fields, keeping the users of your classes from being able to enter corrupt
data into the class that might cause failure later down the road.

Hopefully that helps you understand the difference. Fields and Properties
are always used together and should really be in most class designs, unless
you have no real reason to provide a property to access a field. But the
fields are always there no matter what as a property is useless if it has
nothing to write to.

Good luck and I hope I understood your question.

glenn


"julien" <julien@xxxxxxxxxxx> wrote in message
news:425d54c4$0$1250$636a15ce@xxxxxxxxxxxxxxx
> Hello,
> I don't know when to use fields and when to used properties. It looks to
> me that using properties is always better. But I guess fields must be
> better in some cases, otherwise they wouldn't exist!
>
> Thank you
> Julien


.


Loading