C# Type Casting
Type casting is the conversion of a value from one type to another type. A cast is written in parentheses before the value, like (int).
A cast makes division exact
Division of two ints gives a whole number, so 7 / 2 gives 3. The cast turns 7 into a double first, and the same division gives 3.5.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(7 / 2);
Console.WriteLine((double) 7 / 2);
}
}A cast drops decimals
The cast turns 9.99 into an int. The decimal part drops away, and the result is 9.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int) 9.99);
}
}Convert reads a string
Convert.ToInt32 turns the string "42" into the int 42. Adding 8 then gives a number sum, not joined text.
using System;
class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32("42");
Console.WriteLine(number + 8);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
string text = "17";
int number = Convert.ToInt32(text);
double half = (double) number / 2;
Console.WriteLine(number);
Console.WriteLine(half);
}
}Key points
- A cast in parentheses before a value converts that value.
- A cast to double lets a division keep its decimal part.
- A cast to int drops the decimal part of a value.
- Convert.ToInt32 reads a whole number out of a string.
In this example, Convert.ToInt32 turns the string "17" into the int 17, and the first line prints 17. A cast then turns the number into a double for the division. The second line prints the half, 8.5.
Note
A cast changes the value for that one use. The original variable keeps its own value and type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does (int) 9.99 print?