3.0 Objects

This module will be explaining classes and objects. This is a very important topic when using an object oriented language, like C#.

Objectives

  1. Learn what classes are

  2. Learn what objects are

  3. See how they work together

  4. Have a better understanding of object oriented programming

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 ClassesAndObjects

Classes And Objects

All our code in the previous modules have 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. Lastly, methods and variables that make up a class are referred to as members.

Defining A Class

//    1      2     3
    public class Company
    {
//     4
    }
  1. Access Modifier of class defined

  2. Declaring you are making a class

  3. Name of Class

  4. Body of Class

Create a Class

  1. Right click on your ClassesAndObjects 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 it's own file. Later, we will list properties of a donut within that file.

Next, 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)
        {
            Donut dougDonut = new Donut();
        }

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();
        }

Challenge

Create some other classes and objects in a separate file.

Next: Properties

Last updated