Type Casting
Part of the Fundamentals section of Coddy's C# journey — lesson 14 of 69.
Type casting is the process of converting a value from one data type to another.
In C#, we can convert integers to doubles, doubles to integers, and more. There are two types of casting: implicit (automatic) and explicit (manual) casting.
For example Integer to Double:
Implicit (automatic) casting:
int number = 5;
double decimal_implicit = number; // automatically becomes 5.0
// with calculation
int x = 7;
double result_implicit = x / 2.0; // result is 3.5Explicit (manual) Casting Double to Integer:
double decimal_explicit = 9.7;
int number_explicit = (int) decimal_explicit; // becomes 9 (decimal part is truncated)
// with calculation
double price = 19.99;
int roundedPrice = (int) price; // becomes 19Challenge
BeginnerWrite a C# program that demonstrates type casting. Perform the following operations:
- Declare a
doublevariable namedpriceand initialize it with the value99.99. - Cast the
pricevariable to anintand store the result in a new variable namedintPrice. - Print the values of
priceandintPriceto the console.
Cheat sheet
Type casting converts values from one data type to another. There are two types:
Implicit casting (automatic) - smaller to larger types:
int number = 5;
double decimal_implicit = number; // automatically becomes 5.0Explicit casting (manual) - larger to smaller types:
double decimal_explicit = 9.7;
int number_explicit = (int) decimal_explicit; // becomes 9 (truncated)Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
// Declare and initialize variables
double price = 99.99;
int intPrice = ?;
// Output the values
Console.WriteLine("Price: " + price);
Console.WriteLine("Int Price: " + intPrice);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3