Saturday, June 23, 2012

Casting

Source Code Casting Project

Casting is used for converting between data types. It's used for example when converting from a double to an integer. Doubles are data types that are used for numbers with decimals, like the number 25.5. If you cast this number to an int, then you will lose data, because an integer can't handle decimal numbers. Once you cast the double 25.5 to integer, the integer value will be 25. It will just cut the decimal off.

You can't cast between every data type. It is not possible for example to cast from Random to Button. You can make casting between data types available in the classes you make yourself, but you will have to override something called a cast operator.

There are two different types of casting:
  • Explicit casting
    • Data will be lost when converting. For example when going from a decimal number (double)  to a non decimal number (int). In that case the decimal number will be lost.
  • Implicit casting
    • No data will be lost when converting. If you convert from an integer to a double, then you will not lose any data, because a double is not smaller than an integer.

Create a new console application called "Casting Tutorial".


Add the following method to your Program class:
public static void ShowNumber(int number)
{
Console.WriteLine(number);
}
I know that the public access modifier is unnecessary and that it should be private, but for this example it doesn't really matter. As you can see, this method writes a number on your console application.


Now add the following code to your Main method:
double doubleNumber = 25.5;
ShowNumber(doubleNumber);
If you try to run your application right now, you will receive an error saying that the method ShowNumber only accepts integers and that it can't convert a double to an integer. In order to fix it, you will have to use an explicit cast for converting from a double to an integer.


In order to do so, you will have to replace your Main method's code with the following:
double doubleNumber = 25.5;
int number = (int)doubleNumber;
ShowNumber(number);
Console.Read();
Now your double is converted to an integer using an explicit cast, but of course the decimal number has been lost. Next I want to show you how to use an implicit cast.


For this example you will have to change the ShowNumber method's parameter from double to float and change your Main method so it will look like the following:
static void Main(string[] args)
{
int number = 25;
ShowNumber(number);
Console.Read();
}
public static void ShowNumber(float number)
{
Console.WriteLine(number);
}
It seems like nothing is being cast, but the integer is actually converted to a float using an implicit cast. You can still use an explicit cast, but why would you do that when you have the choice of using an implicit cast with no data being lost.

Knowing the difference between an explicit cast and an implicit cast is nice, but I bet you just want to know how to convert between basic data types. That's why I made you a small list out of the many ways you can convert between certain basic data types:

Code Converts to Description Example
*.ToString() String Almost every class in the .NET Framework has a ToString() method. int number = 25;
string message = number.ToString();
bool.Parse() Boolean Used to convert from almost every basic data type to boolean. bool IsOn = bool.Parse("true");
---
bool IsOn = bool.Parse(0);
//0 converts to false, 1 converts to true
int.Parse() Integer Used to convert from almost every basic data type to integer. int number = int.Parse("25");
---
int number = int.Parse(true);
//false converts to 0, true converts to 1
double.Parse() Double Used to convert from almost every basic data type to double. doublenumber = double.Parse("25");
---
doublenumber = double.Parse(true);
//false converts to 0, true converts to 1
int.TryParse() Integer This method puts the end result of the conversion in the out parameter and returns a boolean to indicate if the conversion has been successful. If you try to use int.Parse("d"); your application will crash, because "d" is not a valid number. This method will not crash your application. int number;
string message = "Hello";
bool isNumber = int.TryParse(message, out number);

A lot of basic types, if not all, have a Parse/TryParse method. Don't think that the Parse/TryParse method only exist for bool, int and double. "char.Parse()" exists as well for example.

Source Code Casting Project

>> Inheritance

2 comments:

  1. Ugh, data types. I always have a hard time picking the right one, especially when it comes to databases. And there's so many variations here and there sometimes that it's just not funny anymore.

    ReplyDelete
    Replies
    1. For some reason I have no problem picking a data type when programming in C#. When setting up a database, I have the feeling I need to think really about which data type to choose. Especially varchar(*) is a nuisance, since I have the need to think of the precise number of characters a field will require.

      Delete