Casting and Converting Between Types
Learn about casting for implicit and explicit conversions, rounding rules, and using System.Convert, parsing from strings to other data types.
We will often need to convert the values of variables between different types. For example, data input is usually entered as text at the console, initially stored in a string
type variable. Still, depending on how it should be stored and processed, it must be converted into a date/time, number, or other data type. Sometimes, we must convert between number types, like an integer and a floating point, before calculating.
Casting
Converting, also known as casting, has two varieties: implicit and explicit.
Implicit casting: Happens automatically and is safe, meaning we will not lose any information.
Explicit casting: This must be performed manually because it may lose information, such as a number's precision. By explicitly casting, we tell the C# compiler we understand and accept the risk.
Casting numbers implicitly and explicitly
Implicitly casting an int
variable into a double
variable is safe because no information can be lost, as the following shows:
Step 1: Use your preferred coding tool to add a new "Console App or console project" named CastingConverting
to the Chapter03
workspace/solution
.
In Visual Studio Code, select
CastingConverting
as the activeOmniSharp
project.
Step 2: In the Program.cs
, delete the existing statements and then type statements to declare and assign an int
variable and a double
variable, and then implicitly cast the integer’s value when assigning it to the double
variable, as shown in the following code:
Get hands-on with 1400+ tech skills courses.