Author: Bjørn Furuknap

How to: Object-Oriented Programming – More with Classes and Objects

Bjørn Furuknap December 7, 2015 by under Cloud Hosting 0 Comments

Bonus Round

Welcome back to our Introduction to Object-Oriented Programming! Perhaps it would be more appropriate to say, “Welcome to the Bonus Round of our Introduction to Object-Oriented Programming!”. This article and the one that follows it are for those of you who want to learn a little more about some of the foundations of Object Orientation and who enjoy some bonus content!

To review, if you’ve followed along with some of the first five articles in this series, then you’ve learned quite a few things:

This article and the next will take what you’ve learned from that introduction and show you more about how you can use some of the principles of object orientation (often abbreviated OO) to make efficient and well-organized code. We will start with a new program that will allow us to review some basic concepts and lead into some new concepts, such as constructors and inheritance.

Again, we’ll be programming in C# using Microsoft’s Visual Studio. If you’d like to follow along (and haven’t done so already) you can find the setup right here.

If you follow the setup in that article up until the “Under the Hood” section, you’ll be right where we’ll be starting. The only thing I will do differently from that article is that I will not be using the default project name “ConsoleApplication1”. Instead, I will call my project “PettingZoo” (in one word) because we will build a petting zoo as our example program.

Note: Object orientation is available in many languages and platforms, and the concepts are very similar. I have chosen C# because it is easy to get started and all the resources you need are free of charge. You may have other languages and platforms you want to use, and that’s fine, too. We’re here to learn object orientation, not any language or implementation in particular.

.

Initial Setup

Before we begin, verify that you have a console application created in Visual Studio. It should look something like Figure 1.

Figure 1: Initial PettingZoo Program Setup

Figure 1: Initial PettingZoo Program Setup

With this console application available in Visual Studio, we can start creating our first class. In C#, there are multiple ways to create a class. In some languages, such as Java, you need to create classes in specific ways using specific file name and folder patterns, but C# just cares that we say that something is a class.

Note that even in the default console application, you already have one class called Program. Using the keyword class followed by the name of the class is how you define a class in C#.

For our approach, we’ll create a new code file to hold our classes. Right-click on the PettingZoo node in the Solution Explorer pane, and then click Add->Class, as shown in Figure 2.

Figure 2: Adding a Class with Solution Explorer

Figure 2: Adding a Class with Solution Explorer

In the dialog box that opens, find the Code element either by searching or navigating, and call your class file something like Animals.cs, as shown in Figure 3.

Figure 3: Adding Class File Dialog Box

Figure 3: Adding Class File Dialog Box

You should now get a new class file created by Visual Studio that contains something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PettingZoo
{
    class Animals
    {
    }
}

Note that by default Visual Studio creates both a class file and a class definition within based on the file name you chose. In some languages–like Java–this structure is a requirement, but in C#, it’s not so strict. We will change the class name in a moment, but leave it for now.

In the file Visual Studio just created, you will notice a number of using statements as well as a namespace code block. These lines aren’t important to our class, but–in case you’re curious–a namespace in C# is a way to organize names in your project. You can have multiple classes with the same name, for example, organized under different namespaces.

As long as you work inside a single namespace, addressing classes is fairly straightforward. But if you need to organize your project into more complex divisions, you may need to utilize different namespaces, in which case the using statements allow you to create shortcuts to those namespaces.

.

Classes and Objects

The file you now have contains a premade class with a name based on the filename you chose. We’re not going to have an Animals class, though, so let’s change that to something else. In a petting zoo, we need dogs, of course, so change the name of the class from Animals to Dog:

class Dog
{
}

Note the change from Animals (plural) to Dog (singular). We will create another class later called Animal, so be careful when you read the code that you pick up on nuances like that.

Before we start adding any content to the class, let’s examine the difference between classes and objects. Remember that a class is the template for how objects should be. A simplistic and not terribly accurate analogy is that of a recipe and a cake.

(This section is a review of classes and objects adapted from the explanation presented in the linked article above. If you want to skip this refresher and get straight to the programming, jump right to the next section! Otherwise, enjoy some cake!)

The recipe tells you how to make a cake and is thus–in OO terms–a class. A cake is the result of the recipe execution and–again, in OO terms–is an object. Another term used frequently is instance, to indicate that the cake is an instance of the execution of a recipe.

As with cakes and recipes, each cake is a unique cake. What you do to one cake does not affect any other cakes. Putting frosting on one cupcake doesn’t mean all cupcakes now have frosting. Similarly, if you eat one cupcake, you still have all the others left.

However, having a recipe and knowing it produces a cake isn’t enough. You also need a kitchen in which to bake the cake. In OO terms, this is the program where you create the object, and in our case, that would be the main Program.cs file.

.

Back to the PettingZoo

Let’s use our new class to create a Dog object, so open the Program.cs file and add the following line inside the static void main code block:

Dog myDog = new Dog();

This line will create a new Dog object from the Dog class and store it in the myDog variable. Let me break this line down into three parts so I can explain what goes on.

[1]Dog [2]myDog = [3]new Dog();

The first element [1], Dog, is the type of variable we want to create. In statically typed languages like C# and Java, we need to declare what type a variable is before we can assign values to it. Languages that are dynamically typed, like JavaScript or Perl, does not require this and puts the responsibility of tracking what type of data a variable contains on the developer.

The second element [2], myDog, is the variable name we use to access the object. This is not necessarily the name of the dog we create but rather what we use to reference this particular instance of a Dog class.

Note: For more on variables and data types like string, check out our introduction to programming article on variables and types.

.
Finally, the third element [3], new Dog(), tells us that we want to create–or instantiate–a new object based on the Dog class. Notice that there are parentheses after the class name, which means this is actually a method. We’ll get back to this method, which is a special method called a constructor (we’ll go deeper into constructors in the next article linked below).

With our program now creating a new object from the Dog class that it stores in the myDog variable, we can start accessing the properties and method of our object. Except, of course, that our class is completely empty and devoid of content! Let’s fix that.
.

Properties and Methods

Let’s go back to our Animals.cs file, where our Dog class has a name but nothing else. However, everything we put inside this code block will become part of the class definition. Remember, classes have properties and methods that define, respectively, what an object is and what it can do.

Let’s create both a property and a method, and then we’ll discuss what each does. Inside your code block’s curly brackets, {}, add the following two lines:

string Name;
void Speak() { Console.WriteLine("Woof"); }

The first line (string Name;) is a property or field. In object orientation, properties define what something is. In our case, we want our dog to have a name, so we have created a string property to hold the name of the dog.

Remember that object orientation seeks to create programmatic representations of real objects. Of course, a name alone does not make a dog, but OO does not seek to duplicate all properties of every object, just those we need. We will add more properties later.

The second line is a method definition (or method signature) and is a bit more complex, so, just like before, let me break it up a bit and show you what each element does.

[1]void [2]Speak() [3]{ Console.WriteLine("Woof"); }

Element [1], void, is the return type of the method, or the type of output that the method will yield when it is executed. In statically typed languages like C# and Java, in addition to declaring variable types, we must always declare what type of data we return from methods. Dynamically typed languages leave the responsibility of determining what comes out of a method to the developer.

In our case, at least initially, we just want the dog to say “Woof” when we ask it to speak, so we don’t need to return anything. This will change later, when we cover inheritance in the next article.

However, even though we don’t want to return any specific value, we still need to be explicit about it in the program. To do so, we can declare that the method returns a void value, which in C# and similar languages means that we’re not returning anything.

Element [2], Speak(), is the method name, and it is what we use to call or execute the method. Note that methods, like properties, belong to the object.

Element [3], the code block, is the code that the program will execute when we call the method. You may also see this sort of code block also called the method body. Right now, within this code block, we’ll just tell the console to write a line containing “Woof”.
.

Making Your Method Public

Now that we have a method, we can call or execute it from our program and have the dog bark. There’s a problem, however, which gives me a great opportunity to review another of the key concepts of object orientation.

Normally, to access properties and methods of an object, you would first write the name of the variable holding your object and then the name of your property or method. For example, to get the value of the Name string property, you could write:

string dogName = myDog.Name;

To execute the Speak() method, you could then write:

myDog.Speak();

However, if you do this in Program.cs, you will get an error message like shown in Figure 4.

Figure 4: Protection Level Error

Figure 4: Protection Level Error

The error, stating “’PettingZoo.Dog.Speak()’ is inaccessible due to its protection level” happens because of a key concept in OO called abstraction.

In short, abstraction takes away the details of how something works when we don’t need to know those details. In our program, we only need to know that the dog can speak, but do not really care about how it does it.

Abstraction instead allows the class designer to come up with access points into the class through which they can work with the objects. Many languages enable this access through access modifiers.

C#, by default, hides properties and methods from outside of the class. The policy on this sort of separation differs in other languages, though, and some languages like JavaScript do not even offer this level of protection.

However, the principle remains that you make public what you want everyone to use and hide the rest. The making public part, in C# at least, simply means adding the keyword public in front of the properties and methods you want someone to access. So, if you update the Dog class to add public in front of the void Speak() line in Animals.cs, the red squigglies go away in Program.cs, as shown in Figure 5.

Figure 5: Public Method Declaration

Figure 5: Public Method Declaration

As an added bonus, when you make your method public, Visual Studio will add the method to the available options through the IntelliSense autocomplete system. When you type myDog and hit the period, you get a list of all public properties and methods of that object, as shown in Figure 6.

Figure 6: Visual Studio Intellisense Auto-Complete with Our New Public Method

Figure 6: Visual Studio Intellisense Auto-Complete with Our New Public Method

Other code editors have similar auto-complete systems. These auto-completes are one of the main benefits of these editors for programmers: you’ll learn to love these features as you evolve as a programmer!

.
Now that we have fixed all the errors, we should be able to run our program and see that the dog barks. You can place a breakpoint in your Program.cs by clicking in the left margin or placing your cursor on the bracket after myDog.Speak() and hitting F9. Then, hit F5 to run the program. You should see the console pop up, and the output from your dog barking should appear, as shown in Figure 7.

Figure 7: Our Dog Speaks!

Figure 7: Our Dog Speaks!

Of course, now we can create a litter of dogs by creating multiple variables and instantiating objects into them. You can try something like Figure 8, for example:

Figure 8: Two Dogs Speaking

Figure 8: Two Dogs Speaking

Got a similar result? Great, pat yourself on the back, but only once, because we still have more work to do. After all, we’ve been promising that object orientation allows us to create unique objects, and all we’ve done is create two identical “dogs”. Next, we’ll show you how to use constructors to create separate and unique objects.
.
.


How to : Object-Oriented Programming – Constructors and Inheritance

Bjørn Furuknap December 4, 2015 by under Cloud Hosting 0 Comments

Previously

We have almost reached the end of our journey through this bonus round of our Introduction to Object-Oriented Programming! In our last article, we started our Petting Zoo example with a review of classes, objects, and methods. If you missed the beginning of this series, you can catch back up with us here. Otherwise, let’s dive back in!
.

Constructors

If you did the exercise with two Dog objects, it was a bit boring, right? After all, we have nothing to separate the dogs from each other and no way of knowing, without looking at the source code, which dog produced which bark.

In the previous article, I mentioned that when you create objects, you call a special method called a constructor. The constructor looks like the class name written as a method. For example, for a Dog class, the constructor would be called Dog().

The special thing about constructors is that they are the path to any new object, so they are a great place to call code that initializes an object with default values. Further, the return value from a constructor method is always an object of the class itself, which is why we can assign the return value of the constructor to a variable of the type of class we create.

However, so far, we have not actually created a constructor at all, so how come we can still call that method?

In many languages, C# included, the language gives you a free and empty constructor without you having to do anything. It is implied that you want a constructor; otherwise there would be no way of using the class for anything, so the languages just assume that you have written one.

This invisible and free constructor is called the default constructor, and, in our example, it will look like this:

public Dog(){ }

Notice that this syntax is very similar to the Speak() method we created earlier, except that we do not explicitly return a value nor do we even declare the return type of the method. As I mentioned earlier, a constructor always returns an instance of the class to which it belongs.

In this case, that is the class Dog, and that is why when we write Dog myDog = new Dog(), we can assign the new object to a variable named myDog which is of type Dog.

So let’s add the default constructor to our Dog class. You can either copy the line above or, in Visual Studio, you can use a shortcut: type ctor and hit Tab twice. It should generate the default constructor for you, as shown in Figure 9:

Figure 9: Adding a Constructor with 'ctor'

Figure 9: Adding a Constructor with ‘ctor’

The default constructor doesn’t actually give us anything new because it is now explicitly doing what was done implicitly before. However, it is a method, so we can now add content inside the brackets that will execute whenever we call this constructor. And because the constructor runs as the very first thing in an object’s construction, it is a perfect place to add initialization code.

For example, we could set the Name property of our objects to something by adding code such as this:

public Dog()
{
    this.Name = "Snoopy";
}

This example will set the Name property of any new objects to “Snoopy”.

Of course, that’s not very useful because not all dogs are called “Snoopy”, so instead, let us change the method signature of the constructor so that it accepts a parameter.

The parentheses of methods aren’t just there to look pretty; they serve to contain parameters that we can use to pass values to a method. This function applies to all methods, not just constructors, but let’s do it for a constructor first.

Change the default constructor signature to this:

public Dog(string dogName)

This addition allows us to send a string parameter into the constructor, and that when we do, we can refer to that parameter by the name dogName.

Then, add the following line to the method block:

this.Name = dogName;

This line sets this object’s property Name to the parameter we sent into the constructor.

Note that when you change the constructor’s signature, you get a case of the red squigglies in your Program.cs file, as shown in Figure 10.

Figure 10: A Case of the Red Squigglies from Our New Constructor

Figure 10: A Case of the Red Squigglies from Our New Constructor

When we add our own explicit constructors, C# and .NET will not implicitly create a default constructor for us. In our Program.cs file, we are still creating the Dog objects using the default parameter-less constructor, which now no longer exists.

To fix this problem, we need to add a parameter to our constructor call in Program.cs. We can, for example, update our object construction line as such:

Dog myDog = new Dog(“Snoopy”);

Doing so will remove the red squigglies and allow you to run the code again. If you leave or set your breakpoint after the last code line, you can look at the Locals panel and verify that your object’s Name property has indeed been set, as shown in Figure 11.

Figure 11: Seeing our Name Property Set Correctly

Figure 11: Seeing our Name Property Set Correctly

Got it? Good! We now have the ability to name our dog, but it isn’t really a useful program if people have to debug it to see what we’re doing. So let’s mix up the code a bit to make sure that we display the name of the dog that is barking.

Update your Dog objects and change the Speak() method as such:

public void Speak() { Console.WriteLine(this.Name + " says: Woof"); }

The change we have made now tells the WriteLine method to concatenate the name of this object with the literal string “ says: Woof” which should give us output that better displays our efforts. Try running the program now, and you should see something resembling Figure 12.

Figure 12: Snoopy Says: Woof

Figure 12: Snoopy Says: Woof

Nice work! You can now create many dogs with different names, and they will all bark at your command.

Of course, a petting zoo with only dogs is somewhat boring. I mean, I love dogs, but maybe we could add some additional animals to spice up the experience a bit?
.

Inheritance

Let’s start out by adding a new Cat class to our Animals.cs file. Add the following code next to the Dog class, but still inside the PettingZoo namespace brackets:

class Cat
{
    public Cat(string catName)
    {
        this.Name = catName;
    }
    string Name;
    public void Speak() { Console.WriteLine(this.Name + " says: Meow!"); }
}

Then, let’s create a Cat object in Program.cs and have it speak:

Cat myCat = new Cat("Garfield");
myCat.Speak();

Running this program now should give you output resembling Figure 13.

Figure 13: Garfield Says: Meow

Figure 13: Garfield Says: Meow

Our program is predictable and works, but did you notice how similar the two classes really are? See how much code we’ve duplicated across the two classes? Wasn’t object orientation supposed to save us from writing code multiple times?

The answer is yes. We can–and should–simplify this code to reduce the amount of duplication. What we are about to go into will demonstrate a feature of OO called inheritance.

Inheritance in object orientation allows you to create a hierarchy of classes and have each class inherit the properties and methods of a parent class. For example, for our petting zoo, we can create a parent Animal class and have Dog and Cat inherit from that class. Then, we can move parts of our code into the Animal class so that both the Dog and Cat classes will inherit that code.

If, however, we move the duplicate parts of our code to this Animal class, then the Dog and Cat classes would each inherit the same properties and methods, making the children clones of the parent classes. This organization isn’t very useful because we want to have distinct types of animals. It would be terribly boring if cats, dogs, and all other animals were the same. In fact, for the purposes of our program, it wouldn’t make sense to call them different things at all.

Now, if inheritance meant that we could only create child classes that were identical to their parent classes, there wouldn’t be much point to going to all of this effort. So while we inherit all parts of a parent class, we can also override certain parts of a parent class in the child classes to make the child classes distinct.

Let’s go through this and see how it works, shall we?
.

Creating Parent and Child Classes

We’re going to take a few steps back and recreate the Dog and Cat classes in a better way. To start off, we need a parent class that will define the shared properties and methods of the child classes.

In your Animals.cs file, remove the Dog and Cat classes and add the following class definition:

class Animal
{
    public string Name;
    public string Sound;
    public void Speak() { Console.WriteLine(this.Name + " says " + this.Sound); }
}

This class looks unsurprisingly like the previous Dog and Cat classes, with the noted exceptions that we have made all properties and methods public and that we have introduced a new property called Sound of type string. Finally, we have updated the Speak method to use the Sound variable.

At this point, your Program.cs will not work and, if you click on that tab, you should see several error messages, which is only natural because we have removed the Cat and Dog classes. Let’s recreate them and do so using inheritance. In your Animals.cs file, right after the Animal class, add the following code:

class Dog : Animal { }
class Cat : Animal { }

These new classes are much shorter than before and do not replicate any code. The new syntax here is a colon followed by the class name Animal, which tells C# that we want both Dog and Cat to inherit from the Animal class. In effect, Dog and Cat become child classes of Animal as illustrated in the diagram shown in Figure 14.

Figure 14: Diagram of Animal Class Inheritance

Figure 14: Diagram of Animal Class Inheritance

Note: I’ve been using the term Property so far, which is slightly inaccurate because the correct term is field as you can see in the diagram in Figure 14. Field is less clear outside the scope of programming, however, so I have used Property instead. Technically, a property is a wrapper around a field in C#.

.
We still have a problem with our Program.cs file, though, because of the custom constructor we created. If you try to run or debug our program, then you should see an error message saying that “‘PettingZoo.Cat’ does not contain a constructor that takes 1 arguments” and similar one for “PettingZoo.Dog”.

To fix this error., we need to add the constructors back in. This time, though, we’re going to utilize inheritance to inherit the constructor and show how you can extend the constructor to change the functionality of a parent class.

First, we need to create a base constructor for Animal, which will resemble the previous constructors we created earlier. Add the following code to your Animal class:

public Animal(string animalName)
{
    this.Name = animalName;
}

As before, our constructor sets the name of the animal to what we pass into it. However, this isn’t enough because we also need to add a constructor to both the Dog and Cat classes. We will use this to define which sound each animal makes too.

class Dog : Animal
{
    public Dog(string dogName) : base(dogName)
    {
        this.Sound = "Woof";
    }
}
class Cat : Animal
{
    public Cat(string catName) : base(catName)
    {
        this.Sound = "Meow";
    }
}

For both classes, we add a constructor that accepts a Name parameter. We also set this object’s Sound property to the sound we want the animal to make.

However, unlike before, we now call the parent class constructor and pass in the Name parameter from the parent constructor. This call comes through the : base() method and by adding the received dogName or catName parameters inside the parentheses.

Note: This : base() syntax is unique to constructors. We will see other ways of changing or extending case functionality later.

.
With these updates to our code, we can now run our program again and see a result similar to Figure 15.

Figure 15: Animals Speak, Using Inheritance

Figure 15: Animals Speak, Using Inheritance

Note that we have neither a Sound nor a Name property defined in either the Dog or Cat classes. We also do not we have a Speak() method. Instead, they reside in the parent Animal class, and the Dog and Cat classes inherit these properties and methods.

We can similarly create other classes now, for any type of animal and we will only need to replicate the pattern of the Dog and Cat classes. For example, we might create these classes:

class Parrot : Animal
{
    public Parrot(string parrotName)
        : base(parrotName)
    {
        this.Sound = "I want a cracker!";
    }
}
class Pig : Animal
{
    public Pig(string pigName)
        : base(pigName)
    {
        this.Sound = "Oink";
    }
}

Then, we can instantiate these classes in Program.cs:

Parrot myParrot = new Parrot("Polly");
myParrot.Speak();

Pig myPig = new Pig("Bacon");
myPig.Speak();

Now we will have a veritable zoo on our hands when we run the program, as shown in Figure 16.

Figure 16: A Zoo of Four Animals Speaking

Figure 16: A Zoo of Four Animals Speaking

You could create further sub-child classes of existing child classes, too. For example, you might separate the Dog class into Beagle and Pointer or have the Parrot class inherit from a parent Bird class that, in turn, inherits from Animal. Creating this sort of hierarchy is beyond the scope of this article, however, so let’s move on and finally look at how we can override, change, or extend the functionality of parent classes in child classes.
.

Modifying Inheritance

We can change the method of a parent class by using a technique called overriding. The syntax for overriding may differ between languages, but the principle of changing the parent’s method in the child class remains the same.

In C#, we add the keyword override followed by the method signature you want to override. We also must declare in the parent class that we are allowing children to override the methods by adding the virtual keyword to the method signature in the parent class. (Other languages may not require this additional indication.)

In our program, we need to update the Speak() method in the Animal class.

public virtual void Speak() { Console.WriteLine(this.Name + " says " + this.Sound); }

Now we can insert our override of the Speak() method in the Dog class at the beginning of our code block for this class.

class Dog : Animal
{
    public override void Speak()
    {
        base.Speak();
        Console.WriteLine("...and then runs around, chasing his tail");
    }
[remaining code omitted]

This code tells us that we want to override what happens in the parent method Speak(). We will still execute the parent method using the base.Speak() call before we output an extra line right afterwards.

Why would you want to do so? Well, perhaps we want our dogs to be as enthusiastic as they can be in person. Run the program and see for yourself:

Figure 17: Our Dog Overrides His Class Method

Figure 17: Our Dog Overrides His Class Method

First, Snoopy barks as normal: the base.Speak() method calls the Speak() method from the parent Animal class. Then the rest of the code outputs a second line to the console. Effectively, we extend the parent class by adding new functionality to the child class only. See how the Cat class is unaffected.

Of course, cats are notoriously difficult to get to do as you wish, so let’s reflect that in code. Update the Cat class and add the following method override, similar to the Dog class.

class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine(Name + " doesn't speak but just sits there wondering when you will feed it.");
    }
[remaining code omitted]

Unlike what we did in the Dog override, we do not call the base.Speak() method this time. Without that call, we never execute the Animal Speak() method and completely change what happens in this method. See for yourself:

Figure 18: Our Cat Also Overrides His Class Method

Figure 18: Our Cat Also Overrides His Class Method

Also notice that as we have rebuilt our classes, we have not changed the Program.cs code. These changes serve as a good example of why object orientation is a very powerful technique; we have completely changed the underlying code without touching the program that uses that code. [Object orientation has allowed us to isolate many of the implementation details and simply expose a small set of interface with which the program needs to interact.]

Where We Bent the Rules

Before we wrap up, I want to point out a few things, chiefly some “bad” things we have done.

First, in our classes, we call the Console.WriteLine() method directly. This usage is not a good design decision because classes should be independent of how we output the results of the classes.

A better approach would be to return data from the classes instead and then output that as part of the program. We would then allow the program to decide what to do with the output rather than the classes, allowing us to use the same classes across many different types of programs, whether they are web pages, Windows Forms, QT, or Console applications.

Second, in our later examples, all the properties were public. Making these properties public weakens the security aspect of object orientation, where we seek to protect the data in the classes from manipulation from the outside. However, protection of properties and methods quickly becomes complex when you are dealing with inheritance so I wanted to avoid that complication, at least at this introductory stage.

Finally, there’s really no point in having Sound set as part of the child constructor at all because we were duplicating that code, too. It would be a better design to create a constructor in the parent class that accepted both a name and a sound, and then just calling that as part of the child constructor. However, again, for the sake of simplicity, I didn’t want to introduce differing constructor signatures at this stage.

So, while we’ve learned a lot in this bonus tutorial, you can see there’s still more to learn. Don’t worry too much about it just yet, however. You can take a moment to congratulate yourself on having followed along all the way. If you have followed all the steps, you have learned:

  • Why we use object orientation
  • How to create classes
  • How to create properties and methods
  • How to create constructors and what they do
  • How to take advantage of inheritance and why it’s a powerful feature of object orientation

I hope you enjoyed this extra lesson and are interested in exploring more. Be sure to check back with us for new content on the Atlantic.Net blog, and consider one our industry-leading cloud hosting servers.
.


How to: Introduction To Programming – Getting Started

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments
Programmer RPG by Walker Cahall

Programmer RPG by Walker Cahall

How-To Series

This is part 1 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

Help! I Have To Become a Programmer!

Let me just quote the late Douglas Adams immediately, because if you are the target audience for this article series, you may just feel a bit nervous right now:

Don’t Panic!

.
You’re going to be fine! I’ll make sure you are well prepared for the tasks ahead. By the end of this series, I’ll have introduced you to programming from a very pragmatic point of view. You will be much better prepared to handle basic programming tasks and understand code when it is thrust in front of you. You’ll understand how programs work and how to build them. You will have seen, if not mastered, many of the concepts of programming so that if nothing else you will know the basics of how these concepts fit into the larger picture of building software.

And it won’t hurt a bit. I promise.

So how did you wind up in this situation? If you’ve read this far, you probably fit into one of several characteristics that make you the perfect audience for this series of beginner programming articles here on Atlantic.Net. For example, you may be sick and tired of doing repetitive tasks when there should be an easier way to do the same thing multiple times. You may want to show that programming dude or gal you know that what they do cannot be that hard, or maybe you really just want to understand how to improve the latest WordPress release. On the other hand, you may just want to learn a bit about how to make machines dance to your tune.

Whatever your background, in this series, I will introduce you to programming. I will do so with a chosen set of tools and languages, not because these tools and language are by any definition “best” or “right”, but because they are simple to use and because learning tools and languages isn’t important in programming at all. Besides, you’ll have plenty of time to develop nearly religious affection for whatever tools or languages you prefer later in life.

As such, I’ve chosen to go with a language called C# (pronounced “See Sharp”) and using Visual Studio for a development environment. To follow along, you’ll need to download a few things to get the same or a similar experience as I show you.
.

Getting Ready

First, you need Visual Studio. Any version will do, but note that they all run on Windows, so you’ll need that.   If you don’t have Windows, you can fire up an Atlantic.NET Windows cloud server and use this.

Now, I’m using Visual Studio 2013, but you can use any variety back to Visual Studio 2003, and they’ll behave more or less the same for our purposes. Most likely, you will want to get one of the newer versions. Unless Microsoft radically changes Visual Studio’s look, any version you get will probably be the close enough to what I’m showing.

Go… Download. Install. Make sure you include at least C#. Other languages are completely optional. I’ll wait right here for you to finish.

Done? Great! Now, you’ve got all the prerequisites for this entire beginner series. Really. Visual Studio contains everything you need to have to start building software, and because it’s all very neatly integrated, it is also very easy with almost zero need for additional setup.

In fact, let’s build a program right now. Three simple steps and you can, technically, put “programming experience” on your resume. Just don’t hope to land any advanced development jobs.

Step 1: Fire up Visual Studio

There’s a splash screen. It takes a few seconds. It may ask you what development setup you want, in which case you can pick any, since it’s likely you don’t have a preference yet.

Step 2: Create a Console Application

When Visual Studio opens, you should see a start page that has a “Start” heading and a “New Project” link, as shown below.

Figure 1: New Project Link in Visual Studio

Figure 1: New Project Link in Visual Studio

Click that link and then browse, search, or find Console Application. Its location differs depending on the version of Visual Studio, but in my version, it’s under Windows Desktop. Select it, leave everything else default, and then click “OK”.

Figure 2: Console Application

Figure 2: Console Application

Visual Studio will take a few seconds to create your project, after which you’ll see the code for your first program, ConsoleApplication1.

Don’t worry about any of the code for now, let’s just get this beast running.

Step 3: Start

Pay close attention to the screen because what happens next happens fast. Hit the Start button where indicated in the menu.

Figure 3: Starting the Program

Figure 3: Starting the Program

What happens next is that a black screen appears briefly and then disappears. That’s fine; we’ll fix that in a moment, but for now, pat yourself on the back and update your resume because you have built your first computer program!

Before we move on and get our program to do something even mildly interesting, let’s examine what you have actually done already, because, despite the way it looked, a lot happened.
.

Under the Hood

Inside your computer is a CPU (Central Processing Unit), which you probably know is the main processing part of your computer. That CPU comprises billions of transistors, which in turn are controlled solely by the flow of electricity. It is a massively complex piece of engineering that has taken thousands of the brightest brains on the planet decades to develop.

The CPU, however, is rather useless on its own. It needs to have the right currents added at the right conductors to be able to do anything. Your job, as a programmer, is to provide it with that current, in the right spot, at the right time.

What you just did was exactly that. The code you see on screen, as simple as it is, is written in a language that is somewhat human-readable. Visual Studio takes care of converting that language into instructions for your CPU by sending your code over to a separate program called a compiler.

The compiler works as a translator between you and the CPU. It can take commands like “Show this on screen” and turn it into operations your CPU understands. This process generates a program, a portable and self-contained piece of software, that you can run at any time.

You have made such a program right now. It is an .exe program, and you can find it by right-clicking on ConsoleApplication1 in the Solution Explorer panel and choosing “Open Folder in File Explorer”.

Figure 4: Locating Your .exe File

Figure 4: Locating Your .exe File

Then, browse into the “bin” (for binary) folder and then into the “debug” folder. You should see your ConsoleApplication1.exe there, proof that you have indeed created your very first computer program, capable of controlling a massively complex computer chip that is the result of millions of hours of work from hardware engineers across time and space.

Figure 5: File Location

Figure 5: File Location

Go ahead, double-click it, and it will act the same way as when you ran it through Visual Studio: up will pop a black window for a brief moment and then disappear. You can take that program file, move it to a different computer, too, and run it–and if you have a compatible system, the program will behave the same.

Before we make any further changes, however, I’d like to point out a couple of important ideas here. What you have created is a binary executable file. A binary executable is usually built to run only on a single type of system. You cannot, for example, take that program file and run it on a Macintosh or a Linux machine without special preparation.

To accomplish platform independence when building software, you need to utilize different methods for turning your program code into instructions for the machine.

In our basic example, we’re relying on Visual Studio to send out program code into a compiler to generate a particular type of executable code. That’s fine for the purposes of learning to program because the concepts are similar across most platforms, and the code we build doesn’t really change that much if we want to build platform-independent code or code that runs in different types of programs.

For example, if you are building web pages, you may build ASP.NET applications instead. The approach to writing the code is very similar but what Visual Studio does behind the scenes produces a different type of executable code. In return, the executable code can run on multiple platforms as long as these support running ASP.NET code. So, for example, you can build code on Windows and run it on Linux using a runtime called Mono.

We won’t go into platform independence in this series, but I wanted to point this out because the way you write code remains very similar, and the concepts you will learn in this series apply to all approaches.

In fact, even if you go outside the Windows and .NET world, you’ll recognize the approaches to programming are very similar. This similarity is why I mentioned earlier that language and tools aren’t really important to programming. If you learn programming, the ideas span not just language, but platform, toolset, runtimes, and devices.

With this understanding in place, we can wrap up this initial article by adding some additional code to our program to make it do something more than just disappear.
.

Why, Hello World!

It is a tradition when learning new programming languages to build a first program called “Hello World!”. The program should do nothing more than print “Hello World!” in whatever way the program outputs text, optionally pausing to wait for the user to acknowledge that they have seen the text. So let’s build that now.

Go back into Visual Studio and take a look at the “Program.cs” file in the left-side pane. Don’t worry about what the code already in place does, but notice that there are curly brackets in lines 12 and 13.

Many languages use such brackets to enclose different parts of a program, and they must always match each left curly bracket (in line 12) to a right curly bracket (line 13). We’ll look more into this later, but for now, just know that the program code we’re about to write goes inside the brackets in lines 12 and 13.

Figure 6: Where To Insert Code Within Program.cs

Figure 6: Where To Insert Code Within Program.cs

Place your cursor to the right of the left curly bracket (as I have done above) and add a couple of blank lines. You can add as many blank lines as you wish; the compiler will just remove any empty lines before building the machine code from it.

Where you added the blank lines, add the following two lines of code:

Console.WriteLine("Hello World!");
Console.ReadLine();

Computers are notoriously bad at inaccuracies so make sure you get it exactly as written above, with the double quotation marks, the parentheses, and the semicolon at the end of each line exactly the way it is. Luckily, if you make mistakes, Visual Studio will often warn you by placing red squiggly lines where you make mistakes and will even tell you what mistake you made.

Figure 7: Example of an Error and the Red Squiggly

Figure 7: Example of an Error and the Red Squiggly

Once you have everything entered correctly, go ahead and click the Start button again. This time, you should see the text “Hello World!” inside the black window. The program should stop when you hit the Enter key.

Figure 8: Your "Hello World!" Program

Figure 8: Your “Hello World!” Program

Congratulations! You have built your first interactive program! Go, you!
.

Introduction To Programming Wrap-Up

In this first article, you’ve already learned a lot about how programming works, not to mention having built your first program! In the next part of this series, we’ll explain more about what you just did and start understanding some of the concepts related to input and output from programs such as these.

Now, don’t forget to save the program before you go out to celebrate with your celebratory beverage of choice. You’ve earned it!

How-To Series

This is part 1 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

How to: Introduction to Programming- Your First Program

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 2 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

You’re Back!

It’s great to see you again, and I hope you have celebrated profoundly after completing the first article in this series at Atlantic.NET in which you built your first program and executed it while learning about how what you build turns from human readable code to machine instructions.

Don’t worry, if you haven’t read that article yet, you can do so now. I’ll wait right here for you to return.

In this part of the series, we’re going to explore that first program more and focus on understanding more concepts of programming and software development. Specifically, we’ll look at input and output, introduce you to a concept called object orientation, and explore how and why we want to hide away complex code using abstraction.

Let’s get down to business, shall we?
.

Digging into “Hello World!”

In the previous article, we built a very basic “Hello World!” program consisting of two lines of code that we wrote ourselves. There were additional code lines, but Visual Studio generated them for us, and they are specific for the type of program we are building and the language we are using, so let us not spend more time on them for now.

The two lines we did add, however, focus specifically on output and input so let us examine them more closely.

Console.WriteLine("Hello World!");
Console.ReadLine();

Ignoring the Console. (read: “console dot”) part of the lines for now, you can see that there is an instruction to the machine to write a line and then to read a line. In a console program or application like the one we’re building now, these are two of the primary ways to interact with the user; we output something on the console screen with Console.WriteLine and get input from the user with Console.Readline. The result looks something like Figure 1 below.

Figure 1: Console output

Figure 1: Console output

This console application is just one of many types of applications we can build. Different application types require different approaches to input and output. If we are building a simple web page, for example, there is no console from and to which we can interact with the user. The web page is just a static piece of text and perhaps some pictures. Although a program may generate it, it is still not very interactive in the same way we build interactivity in a console application.

Note: In the early days of the web, there was a method called CGI (Common Gateway Interface) that allowed you to put console applications like these directly onto a web page and interact with them through the URL.

.

An Example of Web Page Code

A web page has a completely different method of interactive behavior. Look at the following web page code, for example–and don’t worry if this is completely foreign to you:

<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>

This web page simply presents the user with a headline saying “Hello world!” and not much else, as below.

Figure 2: Hello World web page

Figure 2: Hello World web page

On its own, this web page–or even any web page–cannot do much. To create interactivity, browsers can interpret command instructions through languages like JavaScript to manipulate the web page in various ways, including manipulating the web page layout, content, and structure.

For example, below in Figure 3, I’m using JavaScript on an HTML page to display a notification box to the user. Note that I am using Visual Studio to edit the HTML page and the JavaScript too.

Figure 3: JavaScript alert on Hello World page

Figure 3: JavaScript alert on Hello World page

One way that a web page can retrieve information from a user is through web page forms. These may not look like your typical paper forms, but that’s the beauty of the web; it doesn’t need to be boring and daft, it can look stunning and enticing (though the configuration necessary to achieve a stunning and enticing look is beyond our scope here!).

Regardless of appearances, forms can retrieve specific pieces of information from the user that a browser then can send somewhere. If we have, for example, a program somewhere that can read the input from a web page, we can have the browser send the contents of the forms to that program.
.

Event-Driven Programming

Another approach is to use the form data combined with JavaScript to have the web page itself handle the data from the user. Rather than having the JavaScript always display Hello World, for example, we can easily have it display the user’s input into a form.

Figure 4: Dynamic JavaScript alert

Figure 4: Dynamic JavaScript alert

Don’t worry too much about the code here, but note that unlike our console application where the flow of the program is generally line by line from start to finish, in this web page we are using what is known as event-driven programming, by having code respond to events that happen. In the example above, the event onblur happens when the attention shifts away from the input box, and we can write code to react to that event and display the alert.

Regardless, you’ll quickly recognize a certain pattern here that crosses boundaries of platforms, languages, and frameworks. The program starts by presenting the user with a piece of information, and then the user somehow sends instructions to the program. In a console application, this exchange happens through commands such as Console.WriteLine and Console.ReadLine. On the web, this exchange occurs by presenting an HTML page and asking the user to fill in a form.

As a programmer, you’ll learn quickly that what you do as a programmer is very similar across all languages, platforms, and tools. The syntax may differ between languages, and you may have different approaches to how you think in terms of program flow, but behind it all, the computer that you command is the same. It is subject to the same logic regardless of which language you use to manipulate it.

Once you realize that, you may have your Matrix moment, where you see beyond the code and into the machine and the logic behind it and suddenly understand fully how to command the machine in any way you like, using any language, any platform, and any tool.

Before then, though, there’s much to learn. Let’s hop back to our program for a bit because there are some additional things I want to show you.
.

Classes, Objects, and Methods–Oh, My!

We’ll start with the “Console dot” part of the two lines.

Console.WriteLine("Hello World!");

The Console part is a reference to a static class included as part of the System namespace and….

Oh, wait… That makes no sense yet. I need to talk a bit about classes and objects first. I should probably talk a lot about classes and objects, but for now, let’s focus on a basic understanding of what object orientation is because it is prevalent throughout programming languages.

Object orientation is a programming idea that you should build programmatic representations of real life objects and then interact with those objects as if they were the real thing. This definition isn’t terribly accurate, but it serves us well enough for now.

Primarily, we accomplish this interaction with objects through two component types called properties and methods. The good news? You’re already using one of them: the method. In our program here, the WriteLine and ReadLine commands are the methods. Properties, which we won’t really cover in this article, describe what an object is, whereas methods describe what an object can do.

Methods in object orientation are attached to objects or, in some cases, to classes. We will learn much more about methods later in this series, but for now, think of methods as actions that objects can perform.

Further, you can think of the difference between classes and objects as the difference between a cake recipe and a cake, with the recipe being the class and the cake being the object. The class defines how you make an object, just as a recipe defines how you make a cake.

It is somewhat useless to have a recipe but never make anything from it, though. A cake, on the other hand, cannot exist without a recipe. As such, classes and objects, like recipes and cakes, exist in unison.

Where this analogy becomes a bit more complex is when it comes to what we call static classes. These classes, or recipes, are static because they exist as actual things. In fact, you cannot even create objects from them; they exist as recipes only and have static methods only. To complicate matters even further, we can have static methods on regular classes! Confused yet? Well, remember Douglas Adams:

Don’t panic!

.
In our cake analogy, a static method for a recipe may be something that isn’t related to the cake itself but also not necessarily to the recipe. For example, you may attach to the recipe a static method called PointMeToTheKitchen that will–I’m sure you can guess–give you directions to the kitchen. The cake can be baked in any kitchen, and the recipe isn’t dependent on being turned into a cake in any particular kitchen.

To be fair, a better–and yet more complex–situation would be if you have a static class called Baking that handles all the necessary things related to baking with a bunch of static methods, and that the PointMeToTheKitchen method would probably better fit there. In fact, we have that same usage with our current program.

So, to reiterate:
* You use classes to create objects the way you use recipes to create cakes.
* Objects have methods and properties that define what they can do and what they are, respectively.
* Classes can have static methods that exist outside of any object.
* Static classes exist outside everything and exist on their own. You cannot use them to create objects.

We’ll be spending far more time with object orientation towards the end of the series. For now, when I repeat that the Console part of our two lines is a static class, you know that it is a class that exists independent of any object and that it contains static methods, too.
.

Abstrating the Details Away

Look at our lines again:

Console.WriteLine("Hello World!");
Console.ReadLine();

Console is a static class. Its main purpose is to give you access to what you need to deal with the console just like a Baking class would be used to give you access to baking tools.

When we write a dot in C# and many similar languages, we are calling into the method, signified by the following parentheses, or a property. Effectively, we’re saying, “Hey, Console class, let me execute your WriteLine method, please”.

Note: Some languages may use different notation for this. For example in C++, you may use -> instead of a dot in certain contexts, and Perl 5 uses -> consistently.

.
Behind the scenes, the Console class will then, using the parameters we provide (a literal text string “Hello World!”), call into the current console window, do some secret voodoo, and make that console window print the text we sent it, literally “Hello World!”.

In the next line, we call into the same static class Console again, and this time we ask it to call its ReadLine method. In return, the program will instruct the console to wait until we hit the Enter key before advancing in the program. In our case, this input will complete the program and just exit.

We can get into the intricate details of how the console works, but it’s not really relevant at this point. Remember, we’re not here to learn console programming any more than we’re here to learn C#; we’re learning programming concepts. As such, I call it “secret voodoo”–although it certainly isn’t–simply because it’s far enough advanced to us in this context that it might as well be magic.

What you should know, however, is that behind the scenes, these two simple commands actually perform a huge number of tasks. For example, just to interpret the parameters you pass into the WriteLine method, the computer needs to assign a certain memory position to the string, load those characters into that string, and point the execution of the current program to that particular memory location.

The CPU then needs to read out all those memory bits, figure out in what context it is running, call into the operating system (which, in turn, will need to call into the specific hardware you have) to turn on or off the signals that turn each pixel on your screen to its respective color value. And this little excursion isn’t even a fully accurate or complete representation of everything that goes on.

All of these things happen because you wrote a few characters into Visual Studio and hit a button. This peek behind the curtain illustrates another very important principle in programming called abstraction. In short, we want to hide away the intricate details of an operation and interact with it through an easy-to-use method. For outputting content to the console, we hide all the nitty-gritty details into a method called WriteLine.

Two main benefits of abstraction are that we can write a lot less code and that, by not having to repeat the same code every time to achieve the same results, we write better code, too. Behind the scenes, the results we achieve with our simple WriteLine and ReadLine code may take hundreds of lines of code. Having to write all that code greatly increases the chances of making mistakes.

To be accurate, in our example here, it is the .NET team at Microsoft that hides the details for us. In return, they give us a greatly simplified interface with which we can program our applications. Shuffle the words in that sentence around a bit and you might even call it an Application Programming Interface, or API.

Other frameworks have APIs, too. For example, jQuery is an API that abstracts a lot of nitty-gritty details of how JavaScript interacts with content in a web page, like animations, form validations, content manipulation, and so on. OpenGL is an API that abstracts away the interaction with graphics hardware.

There are literally thousands of APIs that give you a way to perform complicated activities. Atlantic.NET has an API for managing your cloud servers, too, so that once you become familiar with programming, you can create programs that start, list, create, or terminate the instances in your Atlantic.NET account.

Note: The Atlantic.NET APIs require working with something called a RESTful interface, which is a bit beyond the scope of these introductory articles.

.

Your First Program Wrap-Up

You’ve had a lot to learn in this article, but now it’s time to take a break. We have discussed in depth how input and output works and given you an introduction to object-oriented programming. You have also learned about the importance of abstraction and how it helps us to avoid mistakes and to simplify our code writing. You have seen how web pages and console applications use different but similar approaches to input and output and had at least a cursory glance at a completely different programming approach called event-driven programming.

In the next article, we’re going to expand on our program by introducing variables and data types, and you’ll start to build a very simple guessing game using these concepts along with what you have already learned.

 

How-To Series

This is part 2 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

.


How to: Introduction to Programming – Object Oriented Programming

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

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

How to: Introduction to Programming – Flow Control

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 4 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

Welcome Back, Aspiring Programmers!

In this article, we’re going to explore control flow and how you can use conditions, branches, loops, and other mechanisms to determine what happens in your program.

If you have not read the previous articles in this series, I strongly suggest you do so. We’re building on top of previous knowledge in all these articles, so it is important for your understanding that you know what we have already covered.

We have a lot to cover in this article, so without further ceremony, let’s get down to business.
.

Handling Exceptions

When we last left our program, we had three lines of code and a problem. The code looks like this:

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = int.Parse(text);

However, if we run this program and enter anything except a number when prompted, the program crashes because the compiler doesn’t know how to turn non-numeric text into an integer.

If you recall from last time, we get what is called an exception, and it is one of the ways we can control the flow of a program in a very specific situation, namely when an exceptional situation occurs.

I wanted to start with exception handling because it is the most complex and possibly confusing topic in flow control, so if you can understand what we do here, you will likely find the remaining concepts much easier to understand.

For exception handling in programming, we have two important ideas you must understand. The first idea is that you can ask your program to try something. The second idea is that if the computer fails at what it is trying, you can catch the problem and handle it.

These two ideas together work a bit like a tightrope walker with a safety net. A tightrope walker (your program) can perform as normal along the tightrope, in most cases. But if something out-of-the-ordinary occurs, such as a misstep off the tightrope (an exception), there should be a safety net to prevent the performer from plummeting to the ground (a catch to handle the exception).

With an understanding of exception handling, we can now begin to see a solution to our problem. We can ask the computer to try to parse the text into an integer, and if it fails–rather than allowing the program to crash–we can catch the mistake, tell the user, and ask them to try again.

Let’s see what that might look like in our code.

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = 0;
try
{
    input = int.Parse(text);
}
catch
{
    Console.WriteLine("Whoops, you didn't enter a number");
}

Our first change is that we are initially setting the int input to zero before we try to set it to the result of the parsing of the text input from the user. There is a specific reason I first set the value to zero and then set it to something else later.

Note that after the try line, the code we want to try is surrounded by curly brackets like these:

{
}

In C# and many similar languages, we use curly brackets to encompass or limit the scope of certain actions, operations, or even variable life cycles. Generally, variables only survive inside these brackets. When our code execution exits a set of these brackets, any variables inside it go away (sometimes called going out-of-scope).

You see the same curly brackets after the catch line, too, which is an instruction that whatever is inside the curly brackets should be executed only if we catch a mistake or an exception. Code inside curly brackets is often called a code block.

What this means is that if we had created the int input inside the try code block, then the variable would just disappear once we had passed the try code block, and we could no longer access it to check if it matches our secret value. I’ll work up an example from our code to show you what I mean. Note in Figure 1 below how I do not define the int input until we are inside the curly brackets of our try statement.

Figure 1: Variable Scope

Figure 1: Variable Scope

Oh, and notice that I have one line that starts with //. In C#, the double slashes indicate that whatever comes after that and until the end of the line is a comment that is not part of the program. The compiler will simply ignore such lines.

.
To try our program out, we can put a breakpoint inside the catch brackets on the Console.WriteLine line, and then execute our program. Enter a non-numeric input to check that rather than crashing, the program now steps into the catch code block, and then eventually displays the error message to the user, as you can see in Figure 2.

Figure 2: Exception caught!

Figure 2: Exception caught!

.

Conditions

Now, this code is rather useless as currently written because we’re reading in a value, but–except for telling the user if they make a mistake–we are not using the value for anything. You can try this and see that if you enter a number, say 7, the breakpoint isn’t hit.

To make our code useful as a guessing game, we need to test whether we have guessed the correct number. Here, we need to introduce a new flow control concept called a condition.

A condition is a code block that executes only if a certain rule or set of rules are fulfilled. We start such conditions with the word if and follow it with the rule or set of rules we are checking in parentheses, which is then followed by the code block we want to execute.

if (condition is met) 
{
    // execute this code block
}

There are, of course, very strict syntax rules for how we can format these conditions, and they aren’t necessarily as intuitive as they could be. For example, to compare values, you need to use two equal signs in C# and sometimes three in JavaScript. (Remember that using one equal sign is how you assign a value.)

if (value == other_value) // example value comparison

You can use a wide range of comparison operators and the rest are a bit more intuitive. For example, like in normal math, you can use greater than (>) and less than (<) and combine these with equal signs to create a greater than or equal (>=) or less than or equal (<=) conditions.

You can also create negative conditions. In many programming languages, you indicate a negative operator with the exclamation point (!), which is also often called a “bang”. For example, if you want to create a condition that executes if two values are not equal, you can write:

if (value != other_value)

You can also create multiple conditions by separating the different conditions using either && (double ampersands) for “AND” conditions or || (double pipes) for “OR” conditions.

if (value1 == other_value && value2 == other_value) … 
//means both value1 and value2 must be equal to other_value

if (value1 == other_value || value2 == other_value) … 
//means either value1 or value2 must be equal to other_value

Using a condition, we can now create a test to see whether the player has guessed the right number. Add the following lines after the last curly bracket of the catch code block:

if (input == 3)
{
    Console.WriteLine("Congratulations! You guessed correctly!");
}

This condition tests whether input (the value the user has entered) equals 3. If this condition is met, the game will display a congratulatory note, as shown in Figure 3.

Figure 3: Condition Met, Congratulations Awarded

Figure 3: Condition Met, Congratulations Awarded

If the user doesn’t guess the number 3, our program displays nothing more, and the application quits.

Remember that you can put breakpoints anywhere in your code to stop execution and see the results of what you are doing. We’ll be doing just that to see the results of the changes we’ll be making to our code from here on out.

.
It would be nice, however, if we could display another message if the user did not guess the correct number. Fortunately, conditions also allow for this behavior through the else keyword.

The else keyword must come directly after an if code block and states what should happen if the condition in the parentheses of an if statement is not fulfilled. To try this out, add the following lines after the if block:

else
{
    Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
}

Your entire conditional code blocks should now look like Figure 4 below.

Figure 4: Guessing Game Program Code with Conditional Code Blocks

Figure 4: Guessing Game Program Code with Conditional Code Blocks

When you execute your program, depending on whether you guess 3, you will get either a congratulation or an encouragement to try again. We call this type of flow control conditional branching because the program goes into one or another branch depending on the conditions you put forth.

Let us increase the odds a bit for anyone who does not know that the magic number is always 3. We will allow multiple attempts at guessing if the player does not guess correctly.
.

Going For a Loop

To accomplish this new functionality, we need to implement something called a loop. In programming, a loop is a block of code that executes repeatedly. Two very common loop types are for loops and while loops.

The best use for for loops are when you have a specific number of times you want something to happen. Let us start with that in our code and see where it leads us.

In a for loop, you need the keyword for followed by a parenthetical block that contains three pieces of information.

First, we define the starting environment for our loop, which includes variables we want to use to keep track of how many times our code block has executed. Second, we want a condition that determines whether we should continue the loop. Finally, we have the changes that we want to make to the loop conditions each time we execute the loop. Let’s look at an example.

for (int i = 0; i < 3; i++)
{
    // This code block will execute three times.
}

The important bit here is the first line. Notice the semi-colons that separate the three parts I mentioned. Here’s how each part breaks down:

int i=0; // Initialization: Creates an integer variable called "i" and sets it to 0.
i<3; // Condition: Continue executing as long as "i" is less than 3.
i++ // Change happening during each loop: "i" increases by one each time the loop runs.

The i++ notation is shorthand for writing i=i+1, which sets i to the value of i plus one–in other words, it increases i by one. You could have written i=i+1 as well, but this particular pattern is very, very common in programming, so I show it as a useful example.

Whatever you put into the block that follows the for loop declaration will happen as long as the condition is fulfilled–in this case, three times. For example, you can add a Console.WriteLine() inside the code block, and it will repeat three times, as in Figure 5 below.

for (int i = 0; i < 3; i++)
{
    Console.WriteLine("I am in a loop!");
}
Figure 5: "I am in a loop!"

Figure 5: “I am in a loop!”

We want to use this sort of loop to allow the user to have multiple tries to guess the correct number. So, we can wrap the entire program we have already written inside a for loop as described above. The code should now look like Figure 6 below.

Figure 6: Guessing Loop

Figure 6: Guessing Loop

Of course, if you guess the correct number before you reach three tries, it makes no sense to keep guessing. As such, we’re about to do a very bad thing….

Remember that the condition for the continued execution is that i remains below 3. So, if we want to stop the loop, we can simply increase i to 3 or more to stop the loop. If you add i = 3 inside the block that executes if the user guesses correctly, as shown in Figure 7 below, the game will stop once the user guesses 3.

Figure 7: Short-Circuiting the For Loop

Figure 7: Short-Circuiting the For Loop

You may not understand why this is a bad idea, and really, it is more of a philosophical argument than a technical one. However, it is an important argument so let’s make it.

A for loop is designed to execute a specific number of times. If you do not know in advance how many times you are going to execute the loop, then a for loop is a poor choice. There are other loop forms that are better suited to this task so using a for loop is picking the wrong tool for the job.

This argument may seem insignificant and pedantic. The program works fine as it is and does exactly what you expect.

However, the programmer’s mind is one that should strive towards clarity, and this example certainly isn’t clear. Looking at the first line of our current code, you think this is a loop that runs three times, but then we “cheat” the loop in the middle so that the loop may run anywhere between one to three times; there is no way for us to know. We have broken the clarity of what will happen, and that’s a bad thing.

Even if you don’t care about anyone reading your code, remember that as programmers, we work with machines that are incapable of understanding intent. It understands exactly only what we say. If we are unclear, the chance that we get unexpected results increases. We risk creating problems for ourselves down the line when programs become more complex.

As such, we need to find a better approach, and that better approach is a while loop.
.

A While Loop

A while loop executes while a condition is true. It doesn’t matter how many times that is: as long as the condition is true, the loop continues.

A while loop is simpler in declaration than a for loop and comprises the keyword while followed by an open parenthesis, the conditions, and a closing parenthesis.

while (condition) 
{
    // Code to execute
}

This execution can be very dangerous if you do not have clear conditions. If you make a mistake or do not properly account for all conditions and events, your program can run amok and grind your machine to a halt.

The danger lies in making sure that you invalidate the condition inside the code block when you want execution to stop. Otherwise, the loop will run forever.

Let’s change our for loop to a while loop and let it run as long as the user has not guessed three times. We can create this condition by declaring an int i=0; before the loop starts and then setting the value of i inside the loop. Update your code as such:

static void Main(string[] args)
{
    int i=0;
    while(i < 3)
    {
        Console.WriteLine("Guess a number between 1 and 10:");
        string text = Console.ReadLine();
        int input = 0;
        try
        {
            input = int.Parse(text);
        }
        catch
        {
            Console.WriteLine("Whoops, you didn't enter a number");
        }
        if (input == 3)
        {
            Console.WriteLine("Congratulations! You guessed correctly!");
            i = 3;
        }
        else
        {
            Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
        }
    }
}

Note that there is a mistake in this code, which shows how easy it is to create infinite loops. We are not increasing i unless we guess correctly! In other words, the player gets infinite tries, but there’s no way to stop guessing if they do not guess correctly!

Luckily, if you start this program, you know the answer is fixed to 3 so you can guess that, but barring that, you might have a huge problem on your hand.

I am saying this not to scare you from using while loops but rather to instill a sense of respect for their power. While loops are very powerful and useful but can also be dangerous if you do not take care.

To fix your issue, add i++; as the first line inside the while code block, immediately preceding Console.WriteLine("Guess a number between 1 and 10:"). Your code should now work as expected, be very clear, and give you a very basic but boring guessing game.
.

A Preview of Object Orientation

So what can we do to make this game even remotely interesting? I know, let’s make the secret number random!

I held back doing this because we need to introduce some new ideas to create random numbers. These ideas will become clear in the next article that deals with object orientation. For now, let me just give you the code and I will explain in detail what it does in the last article of this series.

static void Main(string[] args)
{
    Random random = new Random(); // Object orientation stuff
    int answer = random.Next(10)+1; // Give me a random number less than 10 and add one
    int i = 0;
    while (i < 3)
    {
        i++;
        Console.WriteLine("Guess a number between 1 and 10:");
        string text = Console.ReadLine();
        int input = 0;
        try
        {
            input = int.Parse(text);
        }
        catch
        {
            Console.WriteLine("Whoops, you didn't enter a number");
        }
        if (input == answer)
        {
            Console.WriteLine("Congratulations! You guessed correctly!");
            i = 3;
        }
        else
        {
            Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
        }
    }
}

There are two new lines now and one changed line. The new lines create a random integer answer between 1 and 10, and in the changed line we compare what the user guesses with that random answer.

Don’t worry about the random generation for now, I’ll explain that in the next article. But for now, congratulations, you are hereby officially a game developer in addition to being a programmer! Feel free to play the game now and see how you fare. You should beat the game, on average, 3 out of 10 times.

As an added exercise for yourself, why don’t you add a message after the game ends that tells the player what the secret number was? For now, though, let’s wrap up and go over what we’ve covered.
.

Wrap-Up

In this article, you have learned about program flow and how you can control the flow of your program. You have learned about exceptions for handling mistakes. You have learned about code blocks and conditional branching with if and else. You have also learned about loops with for and while.

In the next article, we will spend a little time polishing the game up, and we’ll also look into object orientation in more detail.

 

How-To Series

This is part 4 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

How to: Introduction to Programming – Variables, Types, and Manipulating Data

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 3 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

Returning to Our Program

In the previous two articles in this series, you have, on average, written one line of code per article. In this one, we’re adding another line, but we’re also going to modify the lines we already have because now we’re going to start talking about variables and data types.

The object of this article is to teach you about variables and types and how to manipulate these to create a program that does more than just print “Hello World!”

We have a lot to cover, so get your fingers ready, and let’s get to it.
.

Using Variables

Our current program remains exceptionally simple with just two lines of code:

Console.WriteLine("Hello World!");
Console.ReadLine();

The first line outputs a piece of text to the console, and the second reads a line from the user. But where does this line that we entered end up? Currently, it just drops out into nothingness because we do nothing to retrieve it, so let’s change that immediately.

Change the second line so that it looks like the following:

String input = Console.ReadLine();

What we are doing here is saying that “String input” (whatever that might be) should be assigned to whatever comes out of the method ReadLine called on the Console static class.

We use the equal sign to assign values in C# and many similar languages. Whatever is on the left side of the equal sign is assigned the value of whatever is on the right side.

The two words in String input have different meanings. String denotes the type of value and input is the name we use to represent the value. What we are doing here is creating a variable called “input” that has a type of “String”. I will explain types later in this article.

In programming, we use variables to hold data in memory so that we can manipulate it easily. You use this in your daily life, too, without actually calling it a variable. Think, for example, of “Your phone”, which is simply an easy way to remember the name for a particular electronic device that may change over time. Or, consider “the US dollar to Euro exchange rate”. You don’t go around remembering that rate all the time, and it changes rapidly, so you probably find it easier to refer to it by name rather than value.

Variables allow us to refer to any particular piece of data by name instead of value, regardless of what the value is or whether it changes. In our program, the data is whatever the user enters before hitting the Enter key. The name we give that particular piece of data, in this case, is “input”, but we can call it different things. In fact, there’s a whole range of patterns just for naming variables, and you’ll probably be very confused by it later on in your career.
.

Debugging with Breakpoints

You can try this out now, but before you do, I want to show you a Visual Studio trick called a breakpoint. A breakpoint allows you to stop the execution of a program and see which line of code is executing–it will even allow you to step through the code line by line from that point.

To create a breakpoint, either move your cursor to the first line of your code and hit F9 or click in the margin to the left of the line numbers on the line where you want to set your breakpoint. If done correctly, the whole line should turn red, and you should get a red circle in the margin.

Figure 1: Breakpoint Added

Figure 1: Breakpoint Added

Note that the breakpoint stops execution before the line at which you set it. Also, breakpoints only work when you run your application through a development tool such as Visual Studio, so if you don’t remove your breakpoints before distributing your application, that’s perfectly fine.

Now, hit F5 or that Start button in the menu and watch your application fire up. Right after it does, Visual Studio should pop back up and show you the next line to execute in yellow.

Figure 2: Breakpoint Hit

Figure 2: Breakpoint Hit

At this point, you can control the execution step by step and observe the results in the console window. To go one step ahead hit F10 in Visual Studio. Bring the console window to the front and observe that your code has now stepped one line ahead, and there’s now “Hello World!” shown in the window as expected.

Figure 3: Next Command Line Executed

Figure 3: Next Command Line Executed

Note: Programmers often refer to this process of hooking into your code as it is executing as “debugging”. This process is one example of the kind of debugging you might do to verify your code is working as expected.

.
Step forward through your code once more in Visual Studio. Notice that as you do, the console window appears automatically. This event happens because the console needs input from the user when executing the Console.ReadLine() method.

Enter any bit of text you like and hit Enter. When you do, Visual Studio will pop back up because now that you’ve provided the input, execution can continue, and we’re still just stepping through the code.

In this Visual Studio window, I’d like to draw your attention to the bottom part of the screen where you should see a tab called “Locals”. If you cannot find it, you can open it by going to the menu and selecting Debug->Windows->Locals or hitting CTRL+D and then L.

Once you open the Locals window, you should see that there is a variable there called “input” that has a value set to whatever you entered in the console window. In my case, I entered “Hi there!”.

Figure 4: Debug Locals

Figure 4: Debug Locals

The Locals tab shows variables that are available to you to use in the current scope. However, before we start manipulating and using this data, it is important to understand the concept of variable types.
.

Variable Types: Static and Dynamic

You see, there are two approaches to what programmers call “typing”, and neither has anything to do with pressing keys on a keyboard. Both approaches have strengths and weaknesses. And no, I’m not going to tell you which is best; you will have plenty of time to determine that yourself, and, perhaps, you may come to understand why some programmers develop an almost fanatical preference for one over the other.

The two approaches are static and dynamic typing. C#, the language you are using in these articles, is a statically typed language, whereas other popular languages like JavaScript are dynamically typed languages. Let me explain the difference.

You noticed earlier that when we created the variable “input”, we decided that it was a String variable. String is a term that serves to indicate what type of data can go into the variable. You cannot add incompatible data to a variable because Visual Studio–or technically the compiler that translates your programming code into machine code–will object and refuse to cooperate.

A String is just a piece of text and can hold almost anything, which makes sense when we’re asking the user to enter any piece of text. However, there’s a potential problem when we want to start working with our data.

Let’s say that we want to ask the user to enter their age and that we want to limit certain functionality if the user is below age 13, for example.

How do you determine whether “Hi there!” is smaller than 13? You cannot, because there’s no way to do arithmetic on a piece of text. “Tomato” plus 45 doesn’t make sense.

A situation such as this one is why statically typed languages have different variable types. We can know whether we can perform arithmetic or other operations on the data before we even send the program to the user.

In statically typed languages, such as C#, VisualBasic, and Java, you must define in advance what a variable can hold, and you cannot create or compile your program without adhering to these rules. In return, you are guaranteed that you won’t be comparing Apples to 3.42 or trying to figure out whether it is legal to sell alcohol to a person who is “none of your business” years old.

In dynamically typed languages, you get no such guarantees. Instead, you just work with variables that can hold any type of data. An example of dynamically typed languages is JavaScript. In JavaScript, programmers need to check that the data they get is of an expected value because their code may crash if they try to add or compare “yes” to 18.

Note: You can actually add “yes” to 18 in most languages, depending on how you do it. You will most likely end up with “yes18”, though, which probably isn’t what you expect.

.
In statically typed languages, you will also find that all methods return a specific type of data–or, in some cases, nothing at all. For example, the Console.ReadLine() method returns a string value, so it works great to set our String input variable to the output from that method just like we did.

However, what will happen if we want to ask the user to pick a number between 1 and 10 because we want to use that number for something later? Let’s start building a simple game and look, shall we?
.

A Guessing Game Program

The game we’re going to build is a guessing game. We pick a secret number between 1 and 10, and then we ask the user to guess which number it is. We’ll make this game more advanced later, so for now, the user just gets one guess and thus has a 10% chance of getting it right. In fact, we’re not even going to test whether they are correct in this article because doing so would involve conditions and flow control, which are concepts we’re not going to learn yet.

First, the variable type for a number that does not have decimals is called an integer, or int for short. An int can hold very large numbers, usually limited by the CPU architecture type, with a 32-bit CPU holding integers up to around 4.4 billion. Beyond that, we can use other variable types. However, for our simple examples, a regular int will work well.

For all types of variables, we can assign simple values directly. For example:

int value = 10; 
string name = “Frank”;

We can also perform operations on variables, as long as they “make sense”. For example, you can add two integer values together.

int value1 = 10;
int value2 = 3;
int value3 = value1+value2;

The integer stored in the variable “value3” is 13 after the portion of code containing these lines runs through this point.

We can also assign values from the return value of methods. Let’s try just assigning the result from the Console.ReadLine() method into an int, shall we? If you haven’t already, stop the execution of your program. We are now going to update our two lines of code as such:

Console.WriteLine("Guess a number between 1 and 10:");
int input = Console.ReadLine();

When you do, you will get a case of the red squigglies (as shown below in Figure 5) and an error message in the Error list stating “Cannot implicitly convert type ‘string’ to ‘int'”.

Figure 5: A Case of the Red Squigglies

We get this error because the value that comes out of the Console.ReadLine() is a string, and the compiler cannot guarantee that it can convert what a user may enter into a number. A user might enter “NO!” for example, and there is no way to turn that input into a number.

There are, of course, ways around this problem. We can force the compiler to accept whatever comes in as being of a specific type. In fact, we can do this with any types. It is a process called casting.

When we cast variable types, the compiler will do its best to convert from one variable type to another. This cast may, for example, work if you have a decimal number and want an integer.

decimal decimalvalue = 3.14M;
int integervalue = decimalvalue;

The first line assigns the value 3.14 to the decimal variable called decimalvalue. The second line tries to assign that decimal value to an integer.

Note: The M is there simply as a hint to the compiler that we are creating a decimal value because, to add even more confusion to this point, there are several types of decimal values, including double precision and floating point values. While useful to know, none of these points are things you’ll need to worry about in this article.

.
If you enter these lines in Visual Studio, you’ll notice that even now, we get a case of squigglies because a decimal value doesn’t fit into an int value. If we tried, we would lose the .14 and be left with just 3 as the value of integervalue.

This behavior may be exactly what we want. In this case, we can cast the decimal value to an int, effectively forcing the compiler to accept the explicit conversion of a decimal value to an integer value. We do so by preceding the value with the type we want in parentheses. Compare these lines of code to the ones from above.

decimal decimalvalue = 3.14M;
int integervalue = (int)decimalvalue;

Now our Visual Studio squigglies will go away, and the compiler is happy. We’re losing some details in the numbers, but you might be confident that this is what you want.

In C#, the compiler will demand that you cast values if there is a chance of data loss, such as is the case if you go from a decimal to an integer value. However, it will gladly accept a compatible conversion when there is no chance of data loss. If you tried to assign an int value to a decimal type, for example, you’d get no quarrel from the compiler.

So far, though, we’re not really getting close to a solution to our problem. We can try to cast the string value coming from Console.ReadLine() into an int, but the compiler will complain that it cannot convert a string value to an integer automatically (as shown below in Figure 6) because there is no way to guarantee in advance that it is possible to turn what comes from the user into a number.

Figure 6: Error with Casting String to Int

Figure 6: Error with Casting String to Int

Fear not, because there’s a better way to solve this! The solution is using a static method to parse the string value into an integer, and it’s located right in the int type itself. As such, we can call on the int.Parse method, send it whatever comes in from the Console.ReadLine() method, and get an integer back out.

So, let’s update your program code to first prompt the user to enter the data, then retrieve the data into a string variable called “text”, and finally to parse “text” into an integer.

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = int.Parse(text);

Once you do, all of your squigglies should go away, and your program should execute as expected. Feel free to set a breakpoint after the last line to stop execution and inspect your variables. See what happens when you enter a number during the execution.

Figure 7: Valid Execution

Figure 7: Valid Execution

You’ll see that “input” now shows that it has a value of 3 whereas “text”, in my case, has a value of “3” (notice the double quotes; double quotes signify a string value).

But what happens if we enter something other than a number? Well, if you enter something like “Hello” instead of a number, the program will crash. In Visual Studio, the execution will stop and tell you about an exception, as shown below in Figure 8.

Figure 8: Invalid Execution

Figure 8: Invalid Execution

As programmers, we don’t want our software to crash, so we need to handle this bug. However, we’re going to leave that for the next article because it involves manipulating the flow of the program, and we’ve already covered quite a bit to get to this point.
.

Variables, Types, and Manipulating Data Wrap-Up

For now, it’s time to wrap up this third article, and despite writing only one more line of code, we have covered a lot of new material. Don’t worry, when I started learning this many years ago, there were many confusing aspects for me, too.

In this article, we have covered the concept of variables and looked at data types and when and why data types are important. You’ve learned about how to create variables and even how to turn data from one type into another through casting. You have learned about step-by-step debugging, breakpoints, and how to inspect available variables in Visual Studio.

You should also note that the things you have learned now are very common across languages and platforms, and I have taken care to introduce and explain concepts that vary, such as static versus dynamic typing.

In the next article, we will look at flow control so that you can learn how to control the execution of your program and check various conditions to determine what the program should do next.

 

How-To Series

This is part 3 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

New York, NY

100 Delawanna Ave, Suite 1

Clifton, NJ 07014

United States

San Francisco, CA

2820 Northwestern Pkwy,

Santa Clara, CA 95051

United States

Dallas, TX

2323 Bryan Street,

Dallas, Texas 75201

United States

Ashburn, VA

1807 Michael Faraday Ct,

Reston, VA 20190

United States

Orlando, FL

440 W Kennedy Blvd, Suite 3

Orlando, FL 32810

United States

Toronto, Canada

20 Pullman Ct, Scarborough,

Ontario M1X 1E4

Canada

London, UK

14 Liverpool Road, Slough,

Berkshire SL1 4QZ

United Kingdom

Resources

We use cookies for advertising, social media and analytics purposes. Read about how we use cookies in our updated Privacy Policy. If you continue to use this site, you consent to our use of cookies and our Privacy Policy.