C# is statically typed at compile time. It means when we declare a variable we cannot declare it again or cannot store data of another data type unless we implicitly change the data type of that variable. This type of conversion operation of a data type is called typecasting.
In c# we can perform the following type of conversion.
C# provides integral which can convert data type within two numeric types. The following table will show the predefined conversion through implicitly
Convert From | Convert To |
---|---|
sbyte |
short , int , long , float , double , or decimal |
byte |
short , ushort , int , uint , long , ulong , float , double , or decimal |
short |
int , long , float , double , or decimal |
ushort |
int , uint , long , ulong , float , double , or decimal |
int |
long, float, double, or decimal |
uint |
long, ulong, float, double, or decimal |
long |
float, double, or decimal |
ulong |
float, double, or decimal |
float |
double |
But there’s a risk of the loss of information during the implicit conversion of the data type.
If we don’t want to lose information during conversion, we will use explicit conversion complier require that you perform conversion of data type which is called a cast.
Following are some examples of method built-in method for the conversion of the data type.
string Numbers = "10";
int Converted_Number = Convert.ToInt32(Numbers);
Console.WriteLine(Converted_Number);
10
int Numbers = 10;
string Converted_Number = Convert.ToString(Numbers);
Console.WriteLine(Converted_Number);
10