What is a field?
A field is a variable of a class. These can be public or private based on how you want the variable to be manipulated in the code. In the GradeBook class from prior posts, the grades variables is a field.
grades is a variable of the class GradeBook thus making it a field.
What is a property?
A property defines a get and/or set accessor. This means it determines how to get the variable(it returns the value) and how to set the value should input be provided.
In the class Person, there is a field called _name which is private meaning it cannot be manipulated outside of the class. Then there is a property called Name featuring a get & set. The get says that if you call variable.Name of which is type Person it will return the value contained by _name. In the set it says that if you give it a string value, the code will set that value equal to _name.
In Main() a variable named Bob is declared as type Person and defined as a new Person() object. Next, Bob.Name is set equal to a string “Bob” and finally the value Bob.Name is written to the console.
When running the application, the name Bob is displayed.
Here is the property defined inside the class again, but a different way. This property is known as an Auto-implemented property which uses a ‘hidden’ field. The C# compiler will automatically create a field during a set and read the value during a get.
When the program is ran with this class auto-implemented property, the result is exactly the same. Using auto-implemented properties, when used correctly, can save a lot of time and lines of written code.