Data Type Casting in C# with Examples: This Tutorial Explains Explicit & Implicit Conversion, Convert To String & Data Type Conversion Using Helper Classes:
Data Types and Variables in C# were explained in detail in our previous tutorial.
We learned how one data type can be converted into another data type by using type casting. Typecasting is divided into two parts i.e. Implicit and Explicit Conversion.
Let us dig deeper into C# Type Casting in this tutorial.
It is implicit conversion when a smaller data type is converted into a larger data type or derived class into a base class.
On the other hand, the conversion in the opposite direction is known as explicit conversion. It needs a cast operator to convert higher data type into a smaller data type. This type of conversion is not type-safe and may result in loss of data.
What You Will Learn:
Data Type Casting in C#
In this tutorial, we will discuss in detail how one type of data can be converted into another data type. C# is static type during compilation, which means after the declaration of a variable it cannot be used to store values of any other data type.
However, this can be overcome by converting that type into a variable type.
Let’s try converting a string value into an integer.
int a; a = "some random string";
If we compile this, it will throw an error stating that “Cannot implicitly convert type ‘string’ to ‘int’.”
Data Types can be further divided based on data types.
Primitive data types are pre-defined whereas non-primitive data types are user-defined. Data types like byte, int, short, float, long, char, bool, etc are called Primitive data types. Non-primitive data types include class, enum, array, delegate, etc.
In this tutorial, we will look into the different methods offered by C# for typecasting.
Implicit conversion is the simplest type of conversion. This type of conversion is type-safe and no loss of data happens during conversion. These conversions deal in converting a derived class to base class.
For Example, we can directly use implicit conversion if the value that needs to be stored in another variable can fit directly without data loss. Let’s say we have an “integer” value and we want to pass that value to a “long”.
int i = 75; long j = i;
In implicit conversion, we saw that we can directly convert a derived class into base class without losing any data but in case if there is a chance of data loss then the compiler will require performing an explicit conversion.
Explicit conversion or cast is a process of passing information to the compiler that the program is trying to perform conversion with the knowledge of possible data loss.
For Example, if we are converting a higher numeric value into a lower one.
double d = 75.25; int i; i = (int)d;
Now, if you print “i”, you will find that it will print “75”. All the data after the decimal will be lost in the conversion.
Conversion Using Different Helper Classes
To convert between different non-compatible types such as converting a string to a number or a byte array into an integer or even hexadecimal strings into other numeric types, we need different helper class as a direct conversion is not possible.
A data type can be converted into another data type by using methods present in the convert class or by using a TryParse method that is available for the various numeral types. TryParse is more useful if we are converting a string into the numeral. It’s pretty straightforward and efficient.
int number = Int32.Parse(“123”);
Here we converted a string into an integer by using parse.
Let’s look at another conversion method which is the Convert method.
Static methods present inside the Convert class are quite useful for converting to the base data type or vice versa. Some of the supported data types are Char, Boolean, Int32, int64, Double, Decimal, String, Int16, etc. Convert class also supports methods for other conversions.
Convert To String
Convert.ToString method converts a data type into a string. In the example below, we are converting an integer data type to a string data type.
int number = 75; string s = Convert.ToString(number);
Sometimes it is possible that the compiler may not understand whether the operation performed to convert one type into another is valid or not. This causes the compiler to fail during the runtime. Once the type conversion fails, it will throw an Invalid exception.
InvalidCastException is thrown whenever an explicit or type conversion implementation is not supported by both the data types used for conversion.
In this tutorial, we learned the types of conversion and how to perform a conversion between different data types. Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type.
Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class. We may need to perform the conversion on different other data types, to do that we take the help of the helper class. Helper class like “Parse” and “ConvertTo” offers various ways to convert one data type into another.
We also learned about the exception that the compiler will throw when it doesn’t understand conversion between two types.