Search⌘ K
AI Features

Type Casting

Learn how to perform type casting in C# to convert values between different data types. Understand narrowing and widening conversions, their risks like data loss and overflow, and how to apply explicit and implicit casts correctly in your programs.

We'll cover the following...

In this lesson, we’ll explore the concept called type casting, where we convert an object of one type to an object of another type.

Consider the following example:

C# 14.0
byte age = 24;
int in10Years = age + 10;
Console.WriteLine(in10Years);
  • Line 1: Initializes a byte variable named age with a value of 24.

  • Line 2: Adds 10 to age. Since arithmetic operations on byte values result in an int, the result is stored in an int variable named in10Years.

  • Line 4: Prints the result, 34, to the console.

It’s safe to assume that the value of in10Years is 34. But, if we change the type of in10Years to byte, our code fails ...