11.0: Properties
In this module we'll introduce properties of a class.
File Location
We will stay in the
10_classes_and_objects
project we created before and build off of that.
Description
Things to think about when writing a property:
What data type will it use?
What will it be named?
Sample Code
In the Donut.cs
file, add these properties. When you are starting to write a property, a shortcut is: Type out prop then hit the tab
key twice:
We've just added 4 properties to the Donut
class. We'll talk about how to use them in a minute, but very quickly let's discuss the get
and set
parts of these properties. These are accessors. This is a bigger topic you will learn more about later. For now, just know that these accessors are used to show that the private fields can be read, written, or manipulated.
Setting Properties
In the Program.cs
file, we've already instantiated 3 new donut objects (Doug's, Chris's and Nick's). Next we will define each of those donuts by assigning values for each property.
We set a property value by doing the following steps: 1. Naming the instance of the class, the object. 2. Use the .
operator to access the specific property. Notice that Visual Studio knows about these properties now. 3. Set the value of the property for this instance of the class.
More Discussion
It's important that you understand this flow: 1. In our Donut
class, we added 4 properties:
A
Filling
property that ispublic
and will hold astring
valueA
Price
property that ispublic
and will hold anint
valueA
Type
property that ispublic
and will hold astring
valueAn
IsSpecial
property that ispublic
and will hold abool
value (true or false)Then we moved to our
Program
file where we already have three objects:dougDonut
,chrisDonut
, andnickDonut
.We set values to these properties of the instantiated objects - i.e.
nickDonut.Filling = "chocolate";
.You can test if these values were set by printing an object's property, i.e.:
Console.WriteLine(nickDonut.Filling);
Challenge
Add properties to the classes you made in the previous challenge and set values to the objects you made with them.
Last updated