How-To Series

This is part 5 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Return for the Final Lesson

Great to see you again! I’m happy that you came back for this final article in this Introduction to Programming series at Atlantic.NET. You’ve learned a lot so far, and this article will be no exception.

In this article, we’re going to explore object orientation, which is a programming methodology where you build out objects that represent the things you want to model and then have those objects perform various tasks.

Want to know the best thing? You’ve already been doing it. Now you just need to understand what you have been doing, and you’ll be good to go.

.

Random Objects

First, recall that in the previous article, I ended by giving you two lines of code that I didn’t yet explain. Here again are the two lines:

Random random = new Random(); // Object orientation stuff
int answer = random.Next(10) + 1; // Give me a random number less than 10 and add one

The first line is the most unfamiliar one to us at this point. We’ll start with the new keyword, which is, well, new. What new does is instantiate an object. Instantiating means creating an instance of something, and in this case, we are creating an instance of a class called Random().

So this first line creates a new object from the Random() class and then assigns it to a variable of type Random and whose name is random. That’s a lot of randomness for a computer that isn’t random at all! This breakdown may help if you find that explanation confusing.

First, you have the variable type. So far we have used int and string types, so here we are introducing a new type–or, really, a class type–called Random.
Second, we have the variable name. When working with variables in earlier articles, we have used variable names such as input and value. Note that in this case, we’re using a variable name of random (we have made it lowercase to try to help you distinguish it), though it could be nearly anything you like, such as number or hey_there_human_can_you_get_me_a_cookie_please_kthxbye.
Third–and this is literally the new part–is how we assign a value to the variable. In earlier articles, we have set this to the output from the Console.ReadLine() method or a fixed value such as 8 or “Hello world!”. Now, we are using a slightly different approach because we are creating a new object with the new keyword.

.

Before we get to the next line, let’s do a little review.
.

A Review of Classes, Objects, Properties, and Methods

In object orientation, the two most important concepts are classes and objects. You learned about this briefly in the second article of this series when I explained that you can think of classes as templates and objects as what you create from those templates, for example, a cake (object) from a recipe (class).

A class, being the template for objects, defines what the objects will be through properties and methods. When you create an object using the new keyword, you get a unique object that has properties and methods as defined by the class.

For example, you may want to create a new cake from a given recipe. By doing so, you can say that you instantiate the recipe and get a cake object. The cake is unique from all other cakes made from that recipe, so changes you make to one cake do not affect any other cakes; putting frosting on one cake does not put frosting on all cakes.

Properties are the values that define what an object is. It may be easier if you think of a property as a sort of variable that is attached to an object. For example, for a cake object, the type of frosting or filling may be a property.

Methods define what an object can do. For example, a car can drive. You don’t really need to know how an engine works; you can simply tell the car to start, and the car will take care of what it needs to do to spin up the engine and get you on your merry way. One of the beautiful things about object orientation is that we don’t really care about the underlying workings of the method, nor do we have to. This is the concept of abstraction that we also discussed earlier.

Because we have already been discussing cakes, we can imagine methods for the cake such as AddFilling and WrapInPaper that would add or adjust the filling property or designate a cake as being wrapped in paper, for example.

.

You can often recognize that you are dealing with objects and classes by the use of periods or “dots”. For example, in the output of our program, we use Console.ReadLine() (spoken as “Console dot ReadLine”). The first part before the dot determines the class or object and the second part after the dot determines the properties or methods we wish to invoke.

How do you tell the difference between properties and methods? Most of the time, methods will have parentheses whereas properties do not. You can tell, for example, that the command Console.ReadLine() asks the Console class or object to invoke the ReadLine() method because “ReadLine” is followed by parentheses.

For properties, you will find that you interact with them much the same way you do with normal variables. You can perform mathematical operations, assign values, read values, and so on, just like with int and string variables. In fact, if you wanted to change up our game code a bit, you could set the properties for the foreground and background colors of the console as such:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;

The addition of these statements will cause the text to be written in white on a blue background the next time you output something in the program, as seen in Figure 1 below.

Figure 1: White on Blue Console Text

Figure 1: White on Blue Console Text

You might have expected the entire window to be blue, right? We get only the output lines blue because we haven’t told the console to clear out any black background that’s already there. We can accomplish this change by calling the Clear() method on the console:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

With this addition, we get something along the lines of Figure 2 below.

Figure 2: Blue Console Window

Figure 2: Blue Console Window

In this example, you use object orientation first to assign values to properties on the console and then to ask the console to do something. This pattern is common in object orientation.

There’s one more thing regarding methods that you need to learn and that is the use of parameters. Fortunately, you have already used a parameter when writing text to the console using the WriteLine() method.

Parameters allow you to configure how a method should execute. For example, when you want the console to write something, you need to tell it what to write. You do so by putting one or more parameters into the parentheses following the method name.

Console.WriteLine(“this is a parameter”);

So far, we have used only fixed text to output something, but we can also pass variables, properties, or even entire objects into methods. For example, the WriteLine() method, can receive an int variable to pass to the console display the value of that variable.

int i = 99;
Console.WriteLine(i);

Exactly what you can do with the various classes and objects vary greatly. You should refer to the API documentation for further reference on what the capabilities of different objects are. Some development tools, such as Visual Studio, can also help you immensely by suggesting values based on what the methods want, or suggest available properties and methods when you start typing an object or class name.

In Visual Studio, for example, you can see all the properties of the console by typing Console and “dot”. Wait for a fraction of a second, and you should see a list of properties and methods and even documentation regarding what the various properties and methods do, as shown in Figure 3 below.

Figure 3: Visual Studio Intellisense Prompt

Figure 3: Visual Studio Intellisense Prompt

In Visual Studio, this feature is called IntelliSense, and if you do your development in Visual Studio, it will be one of the most helpful features you can use. Other development tools offer similar functionality, too.

Finally, there’s one special type of method in object orientation called a constructor. A constructor is a method called when you create an object with the new keyword. This method allows you to perform tasks such as initializing values for the object and is always the first method called in an object lifespan.

.

Back to Our Guessing Game

When we write Random random = new Random(); the Random() part is the constructor. Like other methods, it may accept parameters, which the method can then use to initialize the object’s properties.

Now we can bring it back to the second line we added to create the random integer for our game.

int answer = random.Next(10) + 1;

You may have noticed that when you started typing the text (unless you simply copied it, which is fine, too; just take a look at Figure 4), Visual Studio’s IntelliSense popped up and told you what the Next() method does, as shown below.

Figure 4. Random.Next()

Figure 4. Random.Next()

This hint tells you that the Random.Next() method needs a parameter of type int with a maximum value of “maxValue”. Note that the name stated there is not a type but more of a descriptor–you do not need to call your integer values “maxValue”.

Next, we learn that when we call that method with an int parameter, the method will return to us a nonnegative random integer. In our game, we assign that in a variable name of answer so we can refer to it later.

However, the documentation states that the value returned is less than the maximum. So, when we pass in 10, we get a value that is less than that, so it can only be up to 9. Further, the number returned from Next() is non-negative, so that means it can be 0, and we need a number between 1 and 10, inclusive.

What we get, in other words, when we call random.Next(10) is any number from 0 to 9. Adding 1 to that number means that it will become a number between 1 and 10 before we assign it to answer.

If we now revisit those two lines, it should make more sense what happens:

Random random = new Random();  
int answer = random.Next(10) + 1; 

First, we create a new object based on the Random class, which we call random. Then, we ask that random invokes its Next() method and pass the value 10 into that method. Then, when that method has executed, we add 1 to the result, and then store the value in an int called answer.

That’s it! You’re done! Now, each time you run this program, your user will have to guess at a random value you instructed the computer to generate.

.

See How Far You’ve Come

You’ve built and understood–hopefully–all the aspects of a simple console game. Throughout this series, you have learned many aspects of programming, from how programs execute, how to build applications, how you write code, what code to write, variables, loops, branches, objects, classes.

What you should know, however, is that what you have learned now is merely the foundation of what you need to know as a programmer. Whether you want to start a path as a developer or you just want to learn enough to impress your friends, the lessons in these articles should be a good starting point.

I hope you have enjoyed this series and if you are interested in exploring more. Make sure you check out the other articles in the Atlantic community, too. Wherever this series takes you from here, enjoy your programming! Be sure to check out Atlantic.Net’s market-leading cloud hosting solutions.

 

How-To Series

This is part 5 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming