Skip to content

Implicit and Explicit Conversion

Become a developer with our complete learning paths
Become a developer with our complete learning paths

Intro

This post is an addition to one of the lectures from our C# Masterclass. It also contains the course code and extra explanations.

Type conversion, also known as type casting, is a process in which a value of one data type is converted into another data type. This is a common occurrence in software development, as values may need to be converted to fit the requirements of a specific method or operation. There are two main types of type conversion in C#: implicit and explicit conversion.

 

Implicit conversion

Implicit conversion is a type of conversion that occurs automatically and without the need for explicit casting. This type of conversion is performed when a value can be safely converted from one data type to another without the risk of data loss or other unintended consequences.

Explicit conversion

Explicit conversion, on the other hand, is a type of conversion that requires an explicit cast. This type of conversion is performed when a value cannot be safely converted from one data type to another without the risk of data loss or other unintended consequences.

There are several different methods that can be used to perform type conversion in C#, such as the Convert class and the Parse method.

It is important to note that type conversion can result in data loss or other unintended consequences if performed incorrectly. When performing type conversion, it is always important to consider the potential consequences and take steps to ensure that the conversion is performed correctly.

Source code

// implicit conversion
int number = 123764674;
long bigNumber = number;

float myFloat = 13.37F;
double myNewDouble = myFloat;

Console.WriteLine("My big number {0}",bigNumber);
Console.WriteLine("My new double {0}", myNewDouble);

// explicit conversion
double myDouble = 13.37F;
int myInt;

// cast double to an int
myInt = (int)myDouble;

Console.WriteLine("My int number {0}", myInt);

// type conversion
string doubleToString = myDouble.ToString();
string floatToString = myFloat.ToString();

bool sunIsShining = false;
string boolToString = sunIsShining.ToString();

Console.WriteLine("My bool to string {0}", boolToString);
Console.WriteLine("My float to string {0}", floatToString);
Console.WriteLine("My double to string {0}", doubleToString);

If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide