Menu
Coddy logo textTech

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.5

Explicit (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 19
challenge icon

Challenge

Beginner

Write a C# program that demonstrates type casting. Perform the following operations:

  1. Declare a double variable named price and initialize it with the value 99.99.
  2. Cast the price variable to an int and store the result in a new variable named intPrice.
  3. Print the values of price and intPrice to 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.0

Explicit 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);
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals