Casting is the process when a a value stored in a variable is forced into a variable of a different data type by converting the value to different type.


If you’re using C# for your software development projects, you can perform the following conversions using c#:

  • Implicit: because the conversion is type safe, no special syntax in required and no data will be lost.
  • Explicit (Cast): for explicit conversions a cast operator is required to specify the data type to which the value should be cast. Casting is required when information might be lost in conversion (ex. numeric conversion to a type that has less precision or a smaller range).

There are two other types of conversions:

  • User-defined Conversions
  • Conversions with Helper Class

In this article we will focus on Implicit and Explicit conversions only. So let’s get straight into the code.

Here’s a simple example of implicit and explicit casting in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
double num = 10.5;
int integer = 2;
 
num = num + integer;
Console.WriteLine("Implicit Cast:" + num);
 
num = (double) 7 / integer;
Console.WriteLine("Explicit Cast:" + num);
 
Console.ReadKey();
 
/* 
Output:
 
Implicit Cast: 12.5
Explicit Cast: 3.5
*/
double num = 10.5;
int integer = 2;

num = num + integer;
Console.WriteLine("Implicit Cast:" + num);

num = (double) 7 / integer;
Console.WriteLine("Explicit Cast:" + num);

Console.ReadKey();

/* 
Output:

Implicit Cast: 12.5
Explicit Cast: 3.5
*/

Spread the word!...

I'm an independent software developer living and working in Northampton, England Transylvania, Romania. I am passionate about what I do, it shows in my work and proven track record. If you want to get in touch, drop me a line at me@mvpop.co.uk. I'd love to hear from you.