Basic Program Structure, and Flow Control

Before we get too much further in C# programming, I should probably talk at least a little bit about basic program structure and key words we can utilize to control the flow of a program.

Let’s go ahead and create yet another new Console Project via File -> New -> Project -> Visual C# -> Console Application. Name it whatever you like (I have named mine “ProgramStructure”).  On the right hand side (by default) you will notice a tree heading called References.  Go ahead and expand this and you will see a list of references that are linked to your program (and the .dll files associated with these references):

References

You may have noticed that in the first “Hello World” tutorial, we typed the following:

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

Now take a look at the very top of your newly created Program.cs file. You should see a series of statements like using System; By including this statement, we eliminate the need to fully qualify how we are accessing the Console class. That is, we could easily have just written:

 Console.WriteLine("Hello World!"); 

The using statements you see are provided by default (and change depending upon the project type), but, to be honest these will probably not mean much to you for quite some time. Never fear! We will use them to our advantage later.

Below the using statements, you should see namespace <NameofProject> or, in my case, namespace ProgramStructure. A namespace allows us to qualify completely a method (function) or property that we are attempting to access. For instance, imagine we had written our own version of the Console class–if we were to try and access the Console how would the program know which we were referring to? The using statements covered earlier represent a set of included namespaces (default).

After the namespace declaration, we have the class name that the file (Program.cs) is defining. For a simple console application this doesn’t have much weight, but this will become very important later especially when we start to delve into OOP (Object Oriented Programming) concepts. It is important to know however, that everything in C# is a class.

Try renaming your “Program” class by changing class Program to class whateveryoulike. Will the program still run? You bet! Again, don’t sweat these definitions if you haven’t got the hang of them yet–you will in time!

Inside the class declaration we have a simple function called Main that accepts an array of strings as arguments (potentially). This is the entry-point for the application. Know that we can define any number of methods and properties inside the class declaration, and any number of classes can exist inside a given name space. Organizationally any C# program can be broken down to:

  • Namespaces -> Classes -> Methods, Properties etc

As for controlling the flow of a program, I will cover a few basic concepts:

  • if/then, else statements (This time)
  • switch/case statements (Next time)

If, Else

Say we wanted to test to see if a given player was brain dead or not using a simple console program.  We can do that!  Let’s tart by asking the user (by printing some dialog to the Console) to enter in the number ‘3’.

Console.WriteLine("Hello Adventurer!  Please enter the number '3' to continue!");
Console.ReadLine();

If you run the program now, it kind of sucks! Let’s use Visual Studio’s Intellisense (I will cover this more in detail later) to aid us in seeing what we can do with Console.Readline(). Hover over the ReadLine word and you should see the following pop up:

intellisenseThe keyword on the far left string, tells us what that function returns! We know what a string is! Let’s change the code to the following so we can store the user’s data into a string:

Console.WriteLine("Hello Adventurer!  Please enter the number '3' to continue!");
string response = Console.ReadLine();

Now let’s use an if/then statement to write a message to the screen that is dependent upon the user’s input:

Console.WriteLine("Hello Adventurer!  Please enter the number '3' to continue!");
string response = Console.ReadLine();

if (response == "3")
{
     Console.WriteLine("Congratulations, you are not brain dead!");
}
else
{
     Console.WriteLine("You suck.");
}

Console.ReadLine();

Now, run the program a few times and test to see if your program behaves as you would expect. With the following structure we are telling the program to look at the response given by the user (== indicates an evaluation for equality, while = simply assigns a value), and respond one way if the number “3” is entered. The program will respond in a different kind if ANY other value is entered instead of JUST 3. Remember that the last Console.ReadLine() call is only there to keep the console window from immediately closing.

As an alternative, you can evaluate multiple conditions by including an else if statement.

Say we wanted to modify the program to accept the number 3 or 7:

Console.WriteLine("Hello Adventurer!  Please enter the number '3' or '7' to continue!");
string response = Console.ReadLine();
if (response == "3")
{
     Console.WriteLine("Congratulations, you are not brain dead since you entered 3!");
}
else if (response == "7")
{
     Console.WriteLine("Congratulations, you are not brain dead since you entered 7!");
}
else
{
     Console.WriteLine("You suck.");
}
Console.ReadLine();

There’s a simpler way to evaluate multiple boolean expressions (expressions that return either true or false), which we will cover later!  For now, keep coding!  See if you can modify the program to have a player enter their name, and then have the program write it to the screen!


					

Data Conversions – Explicit and Implicit Casts

Let’s attempt to put to use some of our knowledge on data structures to something useful!  Let’s write a program that calculates the percentage of health that a player has remaining (we can then use this information for something else, like updating a display on the user’s screen).

Start a new console project in Visual Studio, choose a name you like, and then enter the following code blocks inside the brackets of static void Main(string[] args) (the Main function, and entry-point for this application).

The Setup

First, let’s go ahead and define an integer value to contain both the player’s total and current HP (since, fractional health isn’t typically utilized):

// Player's Total HP
int total_HP = 220;

// Player's Current HP
int current_HP = 15;

Now that we have a variable for both the player’s total and current health, we can now calculate the percentage of health the player has remaining by using the following:

// Calculates the % of health remaining
int percent_Health_Remaining = (current_HP / total_HP) * 100;

Simple enough! We could have stored the percentage in a double, but let’s just say for argument’s sake that we don’t care about the fractional percentage component (6% vs. 6.21%). Now, just to verify that our calculation has been performed to our expectation–let’s print the value to the console via:

// Prints the percentage of the player health to the screen
Console.WriteLine("Percent of health remaining: " + percent_Health_Remaining);

// Waits for user input before closing the console
Console.ReadLine();

Now, run your program by pressing F5 or by going to Debug -> Start Debugging. What value did it print? If we perform a hand calculation based on the numbers provided, we should get 6.82%. But why did it print 0?

In order to understand what’s going on, let’s walk through the calculation as the computer does:  The first thing it will do is divide the current_HP value by the total_HP value.  By hand this gives us 0.0682–however, integers can not store fractional components.  At this point the result of the division becomes 0 as the decimal component is truncated.  Multiplying 0 by 100 still gives us the result that we didn’t expect:  0.

How do we fix this?  

As in most cases, there are a lot of ways to fix this.  We could change all the values to double!  That would solve the problem as all the fractional components would carry over to the final equation.  But what if we wanted to keep everything as an integer?

One way to solve this problem without changing data types is to perform what is called as an explicit cast.  An explicit cast is a way to tell your program to treat a value as a different data type.  For the purposes of the calculation that we are trying to achieve, we could change the percent_Health_Remaining calculation to:

int percent_Health_Remaining = (double)current_HP / (double)total_HP * 100;

Now, as you look at this line, Visual Studio will actually underline it and report the following error:

Cannot implicity convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?)

The result of the right hand side of the equal sign is now a double, and Visual Studio is correctly complaining that you can’t implicitly cast from a double to an int.  After all, we are still trying to force a double into an integer which results in a loss of data (due to truncation of the decimal component).  To fix this, encompass the entire right hand side with parentheses and explicitly cast the result of the expression into an integer:

int percent_Health_Remaining = (int)((double)current_HP / (double)total_HP * 100);

Re-run your program, and you should see now that we are achieving the expected result of 6%.  Remember that when explicitly casting from a double to an integer that the fractional component is simply chopped off (no rounding occurs).  This is why the result is 6%, and not 7% as you might expect (we’ll cover a way around this later).

Basic Data Types

With your development environment set up now, we can delve a little further into programming with C# by covering some of the basic data structures:

  • Integers
  • Single precision (floats) and Double precision (doubles)
  • Characters and Strings
  • Booleans
  • Enumerations

For a detailed description of every available data type (reference and value) available to you, check out Microsoft’s Developer Network.

C# is what is known as a strongly typed language (that is, you have to tell the compiler what type of data your variables are storing). For this tutorial and on I will attempt to give the explanations from a gaming perspective (that is, how would what we are talking about be used in a video game?).

Integer Values

Integer values store whole numbers, and are declared as follows:

int currentHP = 500;

Integers are invaluable for storing data related to numbers that should never be fractional (number of items in inventory, number of quests remaining, experience points, gold amount etc.)

Floats & Doubles

Floats (32-bit) and doubles (64-bit) can store very large and very small numbers, but are only accurate to a certain number of digits and are declared as follows:

float percentofhealthremaining = 0.5f;
double attackSpeed = 0.25;

Floats and doubles should be utilized to store information relating to any data member that might end up as a non-integer value.  This could range from a percentage (health remaining, mana remaining) value to calculating a player’s damage per second.

Characters & Strings

Characters and strings store text related data:  A character represents… an individual character or symbol (‘A’, ‘d’), while a string represents an array of character values (“Cloud”):

char battleGrade = 'A';
string charName = "Cloud";

String and character values can be used to store the names of virtually everything in a game environment.

Booleans

Booleans store “True” or “False”:  That’s it!  They are declared as follows:

bool isDead = false;
bool isAggressive = true;

Boolean values should be used to store any value that can simply be true or false (is the character dead, in a town, a criminal, etc.)

Enumerations

Last but not least (and my personal favorite): Enumerations.  Enumerations consist of a series of named values called the enumerator list.  Enumerations are initialized as follows:

enum PlayerClass { Mage, Warrior, Thief, Rogue };
enum MonsterState { Attacking, Dead, WaitingForPlayerInteraction };

Enumerations can add an incredible amount of readability into your code if they are used intelligently.


Next time we will cover basic program flow, and how to control it.

Hello World!

This site is where I will attempt to explain basic to intermediate concepts in C# programming through Visual Studio.

Before you go any further, download and install Visual Studio Express 2013 for Windows.

To begin a new project in Visual Studio (for our tutorial purposes), follow these steps:

  1. File -> New -> Project
  2. Select Console Application
  3. Choose Name, Location, and click OK.

Your screen should look similar to the following (I’m utilizing Visual Studio Ultimate 2013):

IntroScreen

For our first exercise (before we delve into really explaining anything), we’re going to perform the essential “Hello World!” first program.  Enter the following lines of code between the brackets following the static void Main(string[] args) line until the entire program looks like so:

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

namespace HelloWorld
{
     class Program
     {
          static void Main(string[] args)
          {
               System.Console.WriteLine("Hello World!");

               System.Console.ReadLine();
          }
     }
}

Once complete, hit the start button (or hit F5 to compile the program). If everything is set up correctly, you should be greeted with a console window that states, “Hello World!”