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.
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:
Line 1: Initializes a
bytevariable namedagewith a value of24.Line 2: Adds
10toage. Since arithmetic operations onbytevalues result in anint, the result is stored in anintvariable namedin10Years.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 ...