Data Type Conversions
Sometimes we have to change the data that we are using. Sometimes this change may change the value of the data or sometimes it just changes the memory space allocated by that data. This change is called data type conversion.
Data type is converted in 2 ways. They are:
- Implicit conversion
- Explicit conversion
They are described below.
Implicit conversion:
An implicit conversion converts data automatically without losing any data. Normally, data types can implicitly converted into the data types those contain more memory space.
Example:
short firstNumber = 65;
long secondNumber = firstNumber;
Explicit conversion:
An explicit conversion convert data that are automatically can’t be converted. It may converts data from bigger size to smaller size or converts data from one type into totally different type.
Example:
short firstNumber = 65;
long secondNumber = firstNumber; //Implicit conversion
short thirdNumber = (short)secondNumber; //Explicit conversion
Console.WriteLine(thirdNumber); //outputs 65
char a = (char)firstNumber; //Explicit conversion
Console.WriteLine(a); //outputs A
We can use some built in functions those are provided with C#.
a. Convert class:
A convert class contains numerous method those can change one data type into another type. It is another implementation of explicit conversion.
Example:
int number = 65;
char character = Convert.ToChar(number); //Conversion using System’s Class
Console.WriteLine(character); //Output: A
b. ToString() method:
A ToString() method converts any kind of data type into String type. It doesn’t change the internal value of that data.
Example:
char character = Convert.ToChar(65); //Conversion using System’s Class
string numberString = (65).ToString();
Console.WriteLine(character); //Output: A
Console.WriteLine(numberString); //Output(value is in String form): 65
