using property

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

Assume I have some properties in a class and the external object access
these properties.

Now to my question is there any recommendation if internal access from
within the class should use the same property as the external object or can
I use the private fields.

//Tony
 
Tony said:
Assume I have some properties in a class and the external object access
these properties.

Now to my question is there any recommendation if internal access from
within the class should use the same property as the external object or can
I use the private fields.

In most cases it does not make a difference.

I use the private fields, because it seems more logical to
me to use the private access than the external access when
within the class.

If you use automatic properties you have to use the
property for access.

If the property is virtual then there may be a real
difference.

Arne
 
Assume I have some properties in a class and the external object access
these properties.

Now to my question is there any recommendation if internal access from
within the class should use the same property as the external object or can
I use the private fields.

If the property accessors are trivial (i.e. they do the same as if
you'd accessed the field directly), then it usually doesn't matter in
short term. Speed-wise, JIT is going to inline those accessors anyway.

If the property accessors aren't trivial (i.e. they do additional
work, and not simply return/modify the value of the field), then you
have to think about every specific case, depending on what exactly
you're trying to do. Normally, in such cases, all code should go
through the property accessors (after all, that additional work is
there for a reason, right?), except for the code which implements the
property itself - and this can include not just the accessors, but
also some utility methods.
 
Assume I have some properties in a class and the external object access
these properties.

Now to my question is there any recommendation if internal access from
within the class should use the same property as the external object or
can
I use the private fields.

What everyone else said plus:

I think in most cases it is relatively safe to use the internal variable to
READ the property, but you should probably give extra thought every time you
want to WRITE to that variable. I have lots of properties whose get() is
nothing more than a simple "return <variable>;" but whose set() actually
does something beyond "<variable> = value;". In those cases I only write to
the variable explicitly if I need to change its value without invoking the
extra code.
 
Back
Top