10.0: Classes and Objects

In this module we will be explaining classes and objects.

File Location

  1. Right click on the solution you made in the first module.

  2. Go to Add > New Project and select Console App (.NET Framework).

  3. 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

  1. Right click on your 10_classes_and_objects project and go to Add > Class.

  2. Name it Donut.cs.

  3. Add the following code:

public class Donut
{
    //properties will go here in the next module
}

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:

class Program
{
    static void Main(string[] args)
    {
        //1    //2        //3    //4
        Donut dougDonut = new Donut();
    }
}

Analysis

  1. We name the blueprint, the class that we want to instantiate.

  2. We give the object a name, any name will do.

  3. We use the new keyword to instruct that we'd like to make a new instance of the class.

  4. 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:

class Program
{
    static void Main(string[] args)
    {
        Donut dougDonut = new Donut();
        Donut chrisDonut = new Donut();
        Donut nickDonut = new Donut();
    }
}

Here we have created three different instances of the Donut class.

Last updated