C# Properties and Fields

What is a field?

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.

07082014_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.

07082014_PropertyClassNotAutoImplemented

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.

07082014_Property

When running the application, the name Bob is displayed.

07082014_PropertyRan

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.

07082014_PropertyClass

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s