Accessing private attributes from within classes

  • Thread starter Thread starter Beorne
  • Start date Start date
B

Beorne

In the classes I develop my attributes are always private and are
exposed using properties.
From within the class is more correct to access the attributes
directly or to access the attributes using the properties?
Does "wrapper" setter/getter properties introduce time overhead in
execution?

Thanks,
Matteo
 
In the classes I develop my attributes are always private and are
exposed using properties. From within the class is more correct
to access the attributes directly or to access the attributes using
the properties?
Does "wrapper" setter/getter properties introduce time overhead in
execution?

(I'll assume you mean fields or instance variables when you say
attributes - attributes are something else in .NET/C#.)

If your properties are "straight-through" ones which do absolutely
nothing, there shouldn't be any performance hit.

As for whether you should use the fields directly, that depends on
what you're doing. I personally like to do that as it means that if I
add validation at a later date, my private changes will still be
validated. However, there are times you expressly *don't* want to do
this. For instance, suppose you had two fields, first and last, and
your properties made sure that first was never bigger than last. You
might have a SetFirstAndLast method to set them both at the same time,
which would reasonably use the fields directly (or field then
property) to avoid difficulties where setting either property first
would, in some cases, fail validation.

Jon
 
Hi,


Beorne said:
In the classes I develop my attributes are always private and are
exposed using properties.
directly or to access the attributes using the properties?
Does "wrapper" setter/getter properties introduce time overhead in
execution?

If they are just a way to access the internal member you can use it.
Personally I use the Setter method to assign values, it clears the situation
when I add some code later on (either validation, or events). I do not have
that much care when getting the value though. sometimes I nse the member and
some other the property.

Regarding performance problems I would not think about that. Both the
compiler and the JIT compiler will take care of it.
 
(I'll assume you mean fields or instance variables when you say
attributes - attributes are something else in .NET/C#.)

Yes, sorry about the bad naming.

Thank you both very much!.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top