Common Concepts of Programming Part 6 – Object-Oriented Programming Concepts 1

Introduction

Before we get into the grit of this topic, I suggest setting up a new project in our HelloWorld solution. We can call the project HelloObjects. Object-oriented programming is a vast topic, and there is a LOT of ground to cover. The actual depth of this topic goes far beyond what I can put into a single article. So we’ll start here just by creating a single object and interacting with it a bit.

Advanced concepts will be covered down the line to build on this topic; so understanding what we cover here is critical to the process in the long term.

What are Objects?

The concept of object-oriented programming is, as mentioned before, vast. But really what it boils down to is the simple concept that every structure in your program is an object. Well, that sounds interest, but what does it mean?

An object, in programming terms, is a programmatic structure that describes a related set of properties (variables) and methods (functions). Additionally, an object can contain other objects. In more advanced cases, objects can also consist of events – notifications that fire when something has happened within or to the object. That’s something we’ll discuss much later in this series of articles.

Objects also provide the ability to support ENCAPSULATION, which is a way of protecting access to the data that is part of the object, restricting direct control over that data, and more. In many languages, including C#, objects are commonly described in the form of a CLASS. A lot of languages use the CLASS structure t collect a series of related properties and methods, and make them available as a complex data type – they can work much like the string or numeric data we already have used. But whereas a string or numeric value is relatively simple, and really only represents a single value, classes typically are intended to be containers of more complex data.

A simple example of an Object

A great way to examine this concept is to define an object that describes a person. You’re a person (or perhaps a cat walking on the keyboard). I’m a person (most of the time, anyway). You may have a child that is an example of a person; a spouse that is an example of a person. Your mom and dad are also examples.

What do we have in common? We all have a first name, a last name, a date-of-birth, and probably a middle name, too. Those values, our names and date-of-birth, are all properties we have in common. We can all communicate. We can all listen. We can all move (or at least we all have a defined capacity to move). An adult person can have a job. A child person can be a student. A much older adult may have a former occupation. These can be properties as well. But let’s start out by talking about the simple common parts of all (or most) people.

Creating a person class

A person, in programming terms, could be defined with a class containing some properties that all people should have in common. So if we wanted to make a simple C# class for a person, it might start out looking like this.

class Person
{
    public string firstName;
    public string middleName;
    public string lastName;
    public DateTime dateOfBirth;
}

The above code indicates that we have a class called person. This class has 4 properties; 3 strings representing names, and a DateTime data type representing dateOfBirth. This code doesn’t represent a specific person, but is essentially a template for what a person consists of. If we had an application that was going to make sure of this, we could then create a variable of type person.

using System;

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a variable of myPerson; the type of the variable is a Person.
            Person myPerson = new Person();
            //Set value of names
            myPerson.firstName = "John";
            myPerson.middleName = "Michael";
            myPerson.lastName = "Doe";
            //Set date of birth for person
            myPerson.dateOfBirth = new DateTime(2000, 01, 01);

            //Dsiplay back out the person variables values.
            Console.WriteLine("Person's Name: {0} {1} {2}.  Born on {3}", myPerson.firstName, myPerson.middleName, myPerson.lastName, myPerson.dateOfBirth);
            Console.ReadKey();
        }
    }

    // Person class - this is a template of a "person" object
    class Person
    {
        // A property for a person's first name
        public string firstName;
        // A property for a person's middle name
        public string middleName;
        // A property for a person's last name
        public string lastName;
        // A property for a person's date of birth
        public DateTime dateOfBirth;
    }
}

The output of this application would be:

Let’s break down our application example. By now you should recognize that we are using the System library for output. Additionally, you’ll already be familiar with the idea of having a namespace that matches the name of our project: namespace HelloObjects.

And of course, you’ll recognize having a class named Program, with the usual static void main in it. We’ll discuss what’s happening in here in a moment. Let’s jump past it to line 24 and beyond. On line 25, we declare the creation of a class called “Person”.

On lines 28, 30 and 32 we create three string variables; firstName, middleName and lastName. In the terms of object oriented programming, these variables are part of our “Person” object, so we will refer to them as properties of the person object. Finally on line 34, we are creating a property of the type DateTime called dateOfBirth.

You will notice that all of these properties start out with the keyword PUBLIC. We will discuss this keyword and it’s meaning more at a later time. For now, we just need to understand that these properties are directly accessible any time we create a “Person” object. You might also notice that, unlike the “string” keywords, DateTime has a capital D and T, and instead of being blue in Visual Studio, they’ll be green (the colors might be different depending on the theme you selected for appearance, but the significance of a different color is more important than the colors themselves).

A DateTime is a complex type of variable / property. Rather than being something simple like a numeric value, like an INT or FLOAT, or even a STRING, a DateTime is a complex object that has additional properties of its own. Essentially, a DateTime is another type of class, just like our “Person” class. That means it has methods and properties that are part of its structure.

It also should demonstrate to you that an object can actually have other objects as child elements. This is a big deal, simply because it means you can create many different types of structures, which become part of other structures, which in turn become part of other structures, allowing for all sorts of possibilities for complex problem solving.

For now, we’re just treating this as a simple property of our person, and we’ll use it as one more piece of data associated with the Person. I also want you to pay close attention to the fact that our person class does not sit within the program class, but sits separate from it, but still within the same “namespace” container. This means that the Person object is a class that exists independent of the program itself. Later on, we’ll learn how to put these classes in a general space that makes them available in other places in a program.

I also want to note, quickly, that you COULD in theory put the Person class inside of the program class, but that would prevent you from being able to use the person at any point other than inside of the program class. While it might not seem like a big deal, it’s something you should probably avoid doing, as it can lead to all sorts of headaches when you’re trying to solve problems.

Now that we have a definition of a Person object, we’ll go back to the main method for our program, and look at what we do with this object. It’s not a lot, yet, but it’ll demonstrate the basics pretty easily.

On line 10, I create a new “Person” variable called myPerson. We are setting it to a new instance of a Person object. What if we just did the first part and created the myPerson variable, but not the “new” part? Well, nothing would go wrong on that line, but as soon as we tried to set a value of firstName, we’d have a problem. Attempting to assign a value to a property of an object that is not initialized to a new instance of the Person object would give us an error: Use of unassigned local variable myPerson. When we create a variable of a complex type, we need to actually set it equal to a new copy, or sometimes an existing copy, of that object. Without doing this, we’re really saying that we are reserving a placeholder for that type of object, but not really indicating that there is an actual object in that space.

Think of it light a parking space. We say that a parking space is for a vehicle. But if someone tells you to get into the vehicle that is in that parking space, and there is no vehicle there, you have a problem… you can’t get into what doesn’t ACTUALLY exist. So if we were to instead say “This is a parking space with a parked vehicle in it”, we have now initiated the space to have a vehicle that we can then interact with.

So line 10 creates our variable, it creates a new instance or copy of a Person, and we are ready to proceed.

Lines 12 through 14 each set the property of first, middle and last name equal to a value.

Then, we get to line 16. Many of the properties of the DateTime objects are read-only. Year, month, date, hour, minute, second… these are all properties that we cannot directly change. We can only set these values directly when we initialize the DateTime object, which is what I’m doing on that line. I am saying that the value for dateOfBirth will be a new DateTime object with a year of 2000, a month of 01, and a day of 01.

What if you needed to change it later? The simplest solution would be to just set the property equal to a new DateTime with new values. We’ll worry about that sort of complexity at another time.

Finally, we get to line 19, where we print back out the data we stored into our object. Since all of our properties are public, we can just directly pull those values by calling the myPerson object with the .property approach. And of course, line 20 is there so we can see output on the screen without the program immediately exiting.

Conclusion

Although it might not seem it, yet, we just took a MAJOR step in programming. Object-oriented code is a big piece of the underpinnings of most programming languages, especially those used in the software side of development. They are important in hardware development, too, but the value of creating objects and instances will become manifest as time goes on.

The next phase of this process will build on our “Person” object by introducing the idea of “access modifiers”. That is, we start to learn about the significance of the PUBLIC keyword we used above, and start learning the alternative options.