Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Shadab Khan
Shadab Khan
5,470 Points

General rule of thumb for using fields vs properties vs functions ?

Hi, What is the general rule of thumb for using fields vs properties vs functions in C# ? In my understanding, on should use a field to represent a moving part of a class (variable) for e.g. in Treehouse Defense game Invader class; we use _pathStep as a field to increment it everytime we move the Invader using its Move function. Then one should use a property to represent a class's data for e.g. Invader Health property, and should use functions to implement the behaviour of a class which could be a bunch of lines of code. Please give me further advice to cement my understanding.

2 Answers

Steven Parker
Steven Parker
231,110 Points

There's a lot of overlap between these concepts, and many times it's just a matter of "developer's choice". Sometimes the situation will steer the decision, for example a computed property can't take a parameter but a function can. Yet in other situations any choice might work. But as a general rule of thumb:

  • a field stores data associated with an object
  • a property allows special control of the access
  • a computed property allows the data to be accessed in a different form from how it is stored
  • a function should be used when some action or service is being performed
Shadab Khan
Shadab Khan
5,470 Points

Thanks Steven. That helps :)