Educational: Introduction to Classes (Part 2)


Previously, I spoke about classes in .Net (C# specifically) and how they can be used. We started off with a simple class called MyMathClass, which contained one method called Add. This method simply took two integers, added them together, and returned the result to whoever would be calling the method. Remember, methods are containers for logic. They are typically given some parameter(s) to work with and then go they do some logic with them. Methods can manipulate the parameters or use them to do other tasks. They can also return a value to whoever called the method. Methods are created to provide functionality to your program, however, a method is quite useless if no one is calling it. If you had a bunch of math methods in your math class, that doesn’t mean they are being used for anything. A method needs to be called in order to be used. Sometimes you create methods knowing they will be used a lot. Other times you create methods maybe not knowing if they’ll even be used at all. Classes can be libraries as well. A library in programming terms is a class or suite of classes that provide a common functionality when put together. If your boss comes to you and says, “I need you to write me a library that supports basic math functions.” then all your boss is really asking for is for you to create a class or bunch of classes that deliver basic math calculating functionality. You would probably create a math class that has methods for adding, subtracting, multiplying, and dividing. Then, you would deliver this class to your boss or team and say, “Here you go, here’s the library you asked for.” And hopefully there would be no errors in it!

Now I want to focus a little bit of time on how you work with classes. Like I said before, classes are great and all but if no one is actually using the classes you write then what’s the point?

Let’s go back to our example before of a class called MyMathClass

    class MyMathClass
    {
        int Add(int leftHandOperand, int rightHandOperand)
        {
            return leftHandOperand + rightHandOperand;
        }
    }

Just to review. We have a class called “MyMathClass” which contains one method called “Add”. This method takes two parameters (“leftHandOperand” and “rightHandOperand”), both of type integer. This method also returns an integer. Inside the body of the method is some logic that takes the two parameters given to it, adds them together, and returns it.

Now let’s create a program that calls this method by passing in two integers and getting the return value back from it.

If you remember my first hands on lecture then hopefully this is a somewhat of a refresher for you.

Follow these steps carefully so we all stick together.

  1. Open Visual Studio 2010 Express C#
  2. Go to File->New Project (or click Create New Project from the Start screen)
  3. From here click once on “Console Application” to highlight it (do not double-click it yet, if you did, repeat step 2)
  4. At the bottom of this dialog is a Name text box, give this project a name of “MyMathProgram”

You should now have a new project called “MyMathProgram”, which contains a class file called “Program.cs” (the default class added to Console Application project types).

Within that file should be a class called “Program” which contains one method called “Main” (the default method for all Console Application project types).

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add logic here.
        }
    }
}

I added a comment in the body of the Main method to emphasize that we need to do something in there. A comment is a line that the program will ignore when it is running. Comments are really just ways for programmers to communicate with one another. It’s similar to a teacher writing notes on your homework for you to read later. To write a comment in C#, you start off with adding two forward slashes ( // ), then follow it up with whatever you want to say. Comments only work for one line at a time. If you want a multiline comment you’ll need to add another set of forward slashes on the next line. Comments are great and highly recommended for all developer levels. Comments are not just for beginners, sometimes code can be very complex and difficult to understand. Thanks to comments, a good programmer can add comments around their code so another programmer at a later date and time can pick it up and hopefully understand it.

Now let’s go ahead and create another file in our project. This file will be our math class from before which had the Add method in it.

  1. On the right-hand side of Visual Studio you should see a window called Solution Explorer (if you don’t, go to View->Other Windows->Solution Explorer)
  2. Find your project (“MyMathProgram”) and right-click on it
  3. Go to Add->Class
  4. At the “Add New Item” dialog, ensure Class is highlighted (don’t add it yet, if you accidentally did, delete the file from your Project by right clicking on it and selecting Delete)
  5. At the bottom of this dialog you’ll see a Name text box. Give this new class a name of “MyMathClass” (if you don’t specify a file extension, Visual Studio will automatically give it an extension of the file type you have selected in the dialog. Since we should have Class selected it will automatically give the file an extension of “.cs”. If you really want to, you can still specify the file extension and it will use it.

Now if you look at the Solution Explorer you should see that it contains not only the class we were looking at before, but it also contains the one we just added. By default, Visual Studio automatically opens up classes that are added to projects. So let’s go ahead and work with the class that is open now.

Let’s add our Add method back into this class.
We’ll go from this:

namespace MyMathProgram
{
    class MyMathClass
    {
    }
}

To this:

namespace MyMathProgram
{
    class MyMathClass
    {
        int Add(int leftHandOperand, int rightHandOperand)
        {
            return leftHandOperand + rightHandOperand;
        }
    }
}

If you’re confused by this, please see part one of this lecture series. It contains all the information you should need about this class thus far.

So now let’s take a step back and think about what we have so far.

We have a class called “MyMathClass” which contains a method called “Add” which simply adds two integers together and returns the result as an integer.

We also have a class called “Program” which is the heart of our program. When execute this program it will find the Main method in the Program class, and run through it line by line until it gets to the end of the body.

We’re about to do a real example one of the most powerful concepts in programming in decades… object-oriented programming.

We know we have a class that can add two integers together. But how do we use it in another class? If you remember my first hands on lecture where you wrote your first program, then you should remember that in that program we were writing out to our command prompt window (console window) some string of text. We were able to achieve this by using a .Net class called “Console”. We invoked a method off of the Console class called “WriteLine”, which took one parameter… a string of text. That method is part of the .Net Framework, so it’s given to us for free. Calling that method and giving it a parameter is exactly what we are about to do right now with our program.

Let’s go back over to our Program class (double-click on the file “Program.cs” from the Solution Explorer).

We still have this in our Program class:

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add logic here.
        }
    }
}

Now, just like when we used the Console class, we need to now use our own class, the “MyMathClass” class.
I’m probably going to confuse you here, but try to hang in there and I’ll do my best to explain it.

When we used the Console class to call the WriteLine method, we simply did Console.WriteLine(“blah”);
If you were to try and call our Add method from our MyMathClass class in the same way (MyMathClass.Add(1, 1);) then it would fail.

The reason it would fail is beyond the scope of this lecture. If you want to research it, you should look up static methods. A very basic definition of a static method is a method that does not require an instance of its parent class in order to be called. In the case of the WriteLine method from the Console class, WriteLine is a static method. I know it’s a static method because I can use it without creating an instance of the Console class. Creating an instance of a class is another key part of object-oriented programming.

Consider “creating an instance” synonymous to giving birth in real life. When you create an instance of something in programming, you are creating a NEW instance of that class or object. In the case of the WriteLine method, we didn’t create an instance of the Console class to call it. We simply said Console.WriteLine… There is no new instance of Console in that example, therefore the method being called MUST be static.

The reason why you create static methods is when you really don’t want more than one instance of the method to exist out there in the virtual world of your program. Sometimes, it just makes sense to only have one instance. Look at the Console.WriteLine example again. If WriteLine weren’t static, then you would have to create an instance of the Console class just to use the WriteLine method. It seems like overkill to me. WriteLine is a very basic method. It is writing some text out to the console window. In-fact, our Add method in our MyMathClass class is also very simple. It is indeed a good candidate for being static, but we won’t do that (yet). The reason it’s a good candidate to be a static method is because it has literally no dependency on anything outside of its own scope (scope in this case is the body of the method). The method takes two integers, adds them together and returns the sum. It is a perfect candidate for being a static method.

You’ll have better intuition in time and practice of when to use static and when to avoid it. Typically, you’ll use more instanced methods than static methods, but sometimes static methods work nicely.

Anyways, I know I said static is beyond the scope of this lecture and then I went off on a tangent explaining it, but it is indeed beyond the scope of this. I just wanted you to at least be able to look at that keyword and not be completely lost.

So, back to our program. The last thing I said before all the static talk was that until now we’ve only worked with a static method (WriteLine). Since Add is not a static method, we need to create an instance of the class in which Add resides in order to get access to it.

So let’s create an instance of our MyMathClass right now.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMathClass myMathClass = new MyMathClass();
        }
    }
}

Let’s dissect this line. It contains a word “MyMathClass”, followed by the same word but spelled differently “myMathClass”, followed by an equal sign, followed by the word “new”, followed by the same word again “MyMathClass”, followed by an open and close parenthesis, and ended with a semicolon.

First I’ll just say that this entire line is creating a new instance of our MyMathClass, and storing that instance in a variable called myMathClass (with a lowercase ‘m’ at the beginning).
We create instances of objects by starting out the line with the object we want to create an instance from… in this case, “MyMathClass”.
We then type out the name you want to give this new instance. It is common convention to name instances of objects the same name as the object itself, but with a lowercase first letter of the first word (this is called camel case, similar to the appearance of a camel… the first hump on its back is shorter and the next hump is taller, in our case, the first letter of the first word is small, and the first letter of every remaining word is big).

Unfortunately it’s not as easy as just giving your instance a name and ending it with a semicolon. In order to “initialize” your new instance, you must set your named variable to a “new” instance of the class you want to create an instance from. So, we add an equal sign to say, “I want to set my new variable EQUAL to a NEW instance of this class.”.

Now to the parenthesis… you might be asking yourself, “Ummm, why are there parenthesis on this class? It’s not a method… it’s a class!”.
I’m now going to introduce you to constructors. Constructors are pretty much exactly what they sound like. They construct things… in the case of programming, they construct objects. Constructors are methods, but with a catch. Constructors behave and act exactly like methods in every way except two (that are important). First, constructors must have the same name as the class (or object) in which they are constructing. Second, constructors cannot have a return type. What’s this mean? Does that mean it has to return void? No.. it literally means it can’t return anything, not even void (I guess you could argue that all constructors return void by default). If you add “void” in front of a constructor method then it complain when you try to run your program.

So now I hope you’re asking, “So if constructors are methods with the same name as the class they reside in, then how are we calling a constructor here called MyMathClass() when we didn’t even add it to our class?”. Great question if you were thinking that.

The reason why we’re able to call this method without it actually being there is because implicitly (behind the scenes, automatically), every object in .Net has a constructor by default. It’s invisible to you and me, but it’s there. In-fact, it even has a name… it’s called a default constructor. The definition of a default constructor for Java (another programming language, similar to C#) is actually very good. I’m going to paste it here:

In Java (programming language, a “default constructor” refers to a Nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class.The default constructor is also empty, meaning that it does nothing

This applies to our C# example as well. We didn’t define a constructor (method with the same name as the class it resides in) in our MyMathClass class, but one is there anyway by default for us. If you were to write a constructor in our class that had no return type and did nothing (empty body), you would be replicating the default constructor that was created automatically for us.

In-case you were wondering, a default constructor looks like this:

    class MyMathClass
    {
        public MyMathClass()
        {

        }

        int Add(int leftHandOperand, int rightHandOperand)
        {
            return leftHandOperand + rightHandOperand;
        }
    }

Notice it has the same name as our class, and an empty body. It also has open and close parenthesis because it is also a method. The only thing new here is the word “public” in front of it. This isn’t a return type, it’s the accessibility of this method. I will go into public on another part of this series on classes, but for now, just know that public means “anyone can access this member”, and private means “only my closest friends can access this member”. In this case, our class “Program” falls under the category of “anyone” and not “my closest friends”, so in order for us to create an instance of it we must declare this method as public.

Now then, back to our Program class.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMathClass myMathClass = new MyMathClass();
        }
    }
}

We should be pretty familiar with what is going on now. If any of it is rusty or blurry, simply re-read the parts above that pertain to where you are concerned.

At this point, we have an instance of our MyMathClass class called, “myMathClass”.
We can use this instance to access the non-static members of our MyMathClass class. Since we already know nothing in this class is static, then we can access anything from it (that’s public).

Oops, did you see what I just said? I just said that we can only access anything that’s public from our MyMathClass class. Why is that? I briefly explained before the difference between public and private in front of members of classes. In this case, Add is the member we want to get access to. If you go over to our MyMathClass class and look at the Add method, you’ll see that all that’s in front of it is the word “int”. Well, that’s the return type but that doesn’t help us any… You may be asking yourself, “Well if by default, the default constructor is public without telling it to be, shouldn’t everything else be public too?”. Actually, the answer is “no”. Nothing else is public by default. In-fact, everything other than a default constructor is private by default. Default constructors are the exception to the rule. If we want anyone to be able to access our Add method, then we’re going to need to make it accessible… and that means making it public (by the way, this problem that we’re running into now is another key component of object-oriented programming. It’s called, encapsulation. Imagine encapsulation as someone who is holding onto something else very tightly. They are encapsulating that object in their hands, keeping it private. If they wished, they could lessen the encapsulation and make it public for anyone to take. A person controlling the accessibility of the object in their hands in the same as a programmer controlling the accessibility of the objects in their code. You may not want to make everything private or public. Sometimes, exposing some members to the public, and keeping others to yourself is the way to go. Imagine if you had a class that knew some passwords to sensitive information. You probably wouldn’t want to make that public, because then all anyone would have to do would be create an instance to your class and voila… they can get whatever is public. If you kept that information private, then you wouldn’t need to worry because it’s safe from the outside scope of that class.

So before we are able to use our Add method, we need to make it public. Do so now:

    class MyMathClass
    {
        public MyMathClass()
        {

        }

        public int Add(int leftHandOperand, int rightHandOperand)
        {
            return leftHandOperand + rightHandOperand;
        }
    }

Now then, let’s go ahead and access our Add method, and make it perform a 1 + 1 operation in our program.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            myMathClass.Add(1, 1);
        }
    }
}

I added some comments to hopefully give an understanding as to what is going on in our program.
When this program is executed, only two lines will actually be seen by the program… the new instance creation, and the Add() call. The comments will be ignored by the program. They’re only useful for humans, not computers.

Let’s take a look at our new line we added. It starts off with our new instance of our MyMathClass class, and is followed by a period. Remember the period ( ‘.’ ) is how we say, “fetch me the following…”.
We’re basically saying, “Fetch me the Add method from this instance of the MyMathClass class”. We then follow-up the period with the method we want to call, in our case, Add. Inside of this call, we see a 1, a comma, and another 1. If you remember our Add method, it took two parameters, both integers. Well, you can see here that we’re giving our Add method two parameters, both integers as well. So this should be good to go.

We close off the method call with a close parenthesis and a semicolon.

Let’s go ahead and run this program and see what happens.
Press “F5” on your keyboard to run the program.

You’ll notice that once again, the program opened and closed almost immediately. I say “once again” because this happened to us before already, in my first hands-on lecture. The program is closing almost immediately because our Main method is executing the two lines of code it contains and then getting to the end of the body. Once it gets to the end of its body, then there’s nothing left for our program to do… so it exits.

Let’s add a line of code that we added in the hands-on lecture. This line of code will tell our program, “Hey, I know you want to quit, but just sit around and wait for the user to press the Enter key. Once that key is pressed THEN you may exit”.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            myMathClass.Add(1, 1);

            // Tell our program to sit and wait for the Enter
            //  key to be pressed.
            Console.ReadLine();
        }
    }
}

As a quick side note, notice that there’s no instance of the Console class on that ReadLine() method call. You may recall what that means from earlier… ReadLine is a static method!

Anyways, now press “F5” on your keyboard and notice that the program opens and sits there and appears to do nothing (press F5 now).
Well I can tell you it’s not doing nothing, even though it may seem like it visually.

Our program is actually doing 3 things. It’s creating an instance of our class. It’s calling the Add method off that instance, and it’s waiting for the user to press Enter.
Go ahead and press Enter on your keyboard now to allow our program to exit gracefully.

Let’s do one more thing with this program to let the user know it’s actually doing something!
You see the Add() method call in our program? It’s adding 1 + 1 right now, but where’s the answer? Let’s let the user know the answer.

Since we have a Console Application project type, we can utilize the console window (command prompt) for printing out the result of our Add() method call.
Let’s do so now, after the Add() call, but before the ReadLine() call.

namespace MyMathProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of our MyMathClass class.
            //  Store this new instance in a variable called, "myMathClass".
            MyMathClass myMathClass = new MyMathClass();

            // Call the Add method off of our new instance.
            //  Pass in 1 as the leftHandOperand,
            //  and also 1 as the rightHandOperand.
            // Add returns an integer, so let's catch the return value
            //  and store it in an integer variable of our own.
            int sum = myMathClass.Add(1, 1);

            // Take the result of our Add() call and print it to the console window.
            Console.WriteLine(sum);

            // Tell our program to sit and wait for the Enter
            //  key to be pressed.
            Console.ReadLine();
        }
    }
}

I made a change to our Add() call and added comments to reflect that change. I also added the Console.WriteLine call.
So let’s go over these changes.

First, the Add() call clearly has changed. It now has the words “int” and “sum” in front of it.
As you know, “int” is short for “integer”, and is a recognized keyword in C#. We know that our Add() method returns an integer, which is the sum of the two parameters it is given, so this is our way of saying, “This method returns an integer, so I’m going to catch it here.” Now, when Add() is called with 1 and 1 as its parameters, the result of that call will be thrown into our little catch before it, which will be put into the variable we named as “sum”. We could have called it anything, but “sum” is a good choice for the answer to an addition equation.

Now that we have the result to our method call, we can print it out. We can utilize the WriteLine() method off the Console class for that (another static method!).

WriteLine was used in the hands-on lecture. We used it to write out some friendly message to the console window. In that case, the type of parameter we sent to it wasn’t an integer. It was a string. WriteLine() supports many different types of parameters, one of them being string, and conveniently another being integer. So we can pass our integer into this call and it should work just fine.

Go ahead and press F5 on your keyboard now to run the application.
If everything went well you should see a “2” at the top left of your console window!

If not, then go ahead and review the notes above on where you think something may have gone awry.

<closing>

Congratulations! We went over a lot of topics in this lecture. A lot of very basic foundation concepts that a lot of programming is built upon.
We went over classes in-depth, creating members in classes, constructors, encapsulation (public, private), creating instances of objects and using them in other classes, calling members off of an instance of an object, and statically by the use of static methods (the Console class’ WriteLine and ReadLine methods), and a whole lot more!

Thanks for reading, and as usual if you have any questions or comments, feel free to leave them here!

</closing>

Advertisements