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#

drstrangequark
drstrangequark
8,273 Points

Can someone tell me if this understanding of methods vs properties vs fields is correct?

My understanding is that the best time to use each one is as follows:

Fields are used when you want to set an attribute of an object but the user doesn't need to access that attribute (i.e. they will only be used by methods later on but not by the user directly).

Properties ALSO set an attribute of an object but they do it in a way that the user can directly set that attribute and see what it's value is later on as needed (using "get" and "set" methods).

Methods don't set any attributes of an object. They are used to get the object to DO something (even though they can use fields as a way to complete whatever action they have been created to do).

Is that a roughly accurate understanding of why you would use each of them in different scenarios? Could anyone clarify anything I may have missed?

Thank you.

1 Answer

Steven Parker
Steven Parker
229,644 Points

Fields can provide access if they are public.

Properties also may or may not provide access based on their public/private setting, plus they can have different settings for the "get" and the "set" capabilities.

And whether a method provides access or does something is up to the method coding. It might do both.

drstrangequark
drstrangequark
8,273 Points

Gotcha. So that being said, what's the functional difference between when you would use each of them if they are all capable of the same thing?

Steven Parker
Steven Parker
229,644 Points

Many times you want features of a property, such as public get but private set, or computed values. But for occasions where only storage with totally public access is desired, simple fields might be slightly more efficient.