11.0: Properties
In this module we'll introduce properties of a class.
File Location
We will stay in the
10_classes_and_objectsproject 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:
class Donut
{
//Properties
public string Type { get; set; }
public string Filling { get; set; }
public decimal Price { get; set;}
public bool IsSpecial { get; set; }
}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.
class Program
{
static void Main(string[] args)
{
//Instantiating the objects
Donut dougDonut = new Donut();
Donut chrisDonut = new Donut();
Donut nickDonut = new Donut();
//setting property values
//1 //2 //3
dougDonut.Filling = "cherry";
dougDonut.Price = 3;
dougDonut.Type = "normal";
dougDonut.IsSpecial = true;
chrisDonut.Filling = "none";
chrisDonut.Price = 2;
chrisDonut.Type = "small";
chrisDonut.IsSpecial = false;
nickDonut.Filling = "chocolate";
nickDonut.Price = 3;
nickDonut.Type = "normal";
nickDonut.IsSpecial = true;
Console.WriteLine(nickDonut.Filling);
}
}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
Fillingproperty that ispublicand will hold astringvalueA
Priceproperty that ispublicand will hold anintvalueA
Typeproperty that ispublicand will hold astringvalueAn
IsSpecialproperty that ispublicand will hold aboolvalue (true or false)Then we moved to our
Programfile 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