Protected/private field vs public property

  • Thread starter Thread starter Gawel
  • Start date Start date
G

Gawel

Let say I have:

public class Class1
{
protected int _counter;

public void MakeSomethingWithCounter()
{
_counter = 10;
or <--------------------------which way is morr accurate ?
Counter = 10;
}

public int Counter
{
set { _counter = value; }
get { return _counter; }
}
}

What kind of approach should I choose ?
Property or field ? Property is a method, therefore
using property can be less efficient.....but I can be wrong.


Gawel
 
What kind of approach should I choose ?

Personally I tend to use the variable directly unless I want to run
any validation code I might have in the property.

Property or field ? Property is a method, therefore
using property can be less efficient.....but I can be wrong.

For simple accessors like the one you had, the variable access is most
likely inlined and so there's no actual performance penalty in using
the property.



Mattias
 
If you think a level of indirection may be useful in the future or you
want read
only/set only behavior, also consider using a property. I believe that
you can
declare a property as virtual, so that you can override a property.
Shadowing
a field gives you different behaviour.

http://www.geocities.com/jeff_louie/OOP/oop8.htm

Regards,
Jeff
 
public class Class1
{
protected int _counter;

public void MakeSomethingWithCounter()
{
_counter = 10;
or <--------------------------which way is morr accurate ?
Counter = 10;
}

public int Counter
{
set { _counter = value; }
get { return _counter; }
}
}

What kind of approach should I choose ?
Property or field ? Property is a method, therefore
using property can be less efficient.....but I can be wrong.


You should always only use the property unless you explicitly don't want to
run validation code or similar.
Properties are mostly inlined so there is no performance penalty.
 
You should always only use the property unless you explicitly don't want to
run validation code or similar.
Properties are mostly inlined so there is no performance penalty.

Thank you all.


Gawel
 

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