10.0: Classes and Objects
In this module we will be explaining classes and objects.
File Location
Right click on the solution you made in the first module.
Go to Add > New Project and select Console App (.NET Framework).
Name it
10_classes_and_objects
.
Description
All our code in the previous modules has been written within classes whether you realized it or not. Classes and objects are some of, if not the most important aspects within the C# language. Since C# is an object oriented language, it would make sense that it is important to get a well rounded understanding of the two.
Classes are often described as the blueprint of your data types. They are a main component of how your program and data will be organized. This does not specifically define any real data but it will define what the class name means.
Objects are an instance, or single occurrence of a class. We can create as many objects as we want, based on a class.
Create a Class
Right click on your
10_classes_and_objects
project and go to Add > Class.Name it
Donut.cs
.Add the following code:
Discussion
Above we have created a class called Donut
in its own file. Later, we will list properties of a donut within that file. For now we can still make objects from the class. We call this process instantiation.
We need to instantiate Objects in the Program.cs
file. 1. Go to the Program.cs
file. 2. Add this code:
Analysis
We name the blueprint, the class that we want to instantiate.
We give the object a name, any name will do.
We use the
new
keyword to instruct that we'd like to make a new instance of the class.We call to the constructor function(more on this at another time) and create the new instance.
Above we made an object off of the class Donut
. We can add other objects as well:
Here we have created three different instances of the Donut
class.
Last updated