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!”