3.1 Properties
Objectives
Learn why we use properties
Learn the syntax of writing a property
File Location
We will stay in the ClassesAndObjectsPractice project we created before and build off of that.
Description
Things to think about when writing a property:
Will it be public or private?
What data type will it use?
What will it be named?
Add the get and set accessors
Visualization
Access Modifier
Property DataType
Name of Property
Accessor
Accessor
Accessors are the second half of the syntax used when writing a property. It looks like this { get; set; }
. 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.
When you are starting to write a property, a shortcut is: Type out prop then hit the tab
key twice.
Sample Code
In the Donut.cs
file, add these 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.
Discussion
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 Console.WriteLine'ing the object's property
Console.WriteLine(nickDonut.Filling);
Challenges
Bronze Challenge
Add a class called Hotel
Create three properties/variables:
RoomNumber
IsAvailable
NumBeds
Create an object and give each property a value
Silver Challenge
Create a method that prints out the
RoomNumber
to a guestFor instance, "Your room number is C24".
Gold Challenge
Create a method that checks the availability of a room and prints the following:
"Yes sir (or miss, but NOT ma'am - no one wants to be called ma'am), room A23 is available." -> If it is available.
"I'm sorry sir (or miss), that room is not available." -> If it is not available.
Answers
Next: Methods
Last updated