Data Type Conversion
In our previous tutorial we have seen various types of data and how to use them. In this session we are going to look into how to convert these data type from one to another.
Implicit Conversions
In Implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off.
We can take example of int and long, float and double.
we can declare a variable int and assign it to a long type which is an implicit conversion as the scope of long is bigger than that of int so there is no worry of loosing data.
Explicit Conversions
However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted.
We can take the below example to convert data types from int to long and float to double at the same time we can see the example of long to int and double to float. It shows how both type of conversions work.
Conversion methods in C#
The following table lists some of the methods from the Convert class that you can use.
How to convert a String to a Number
Comments
Post a Comment