Conversion Using the Convert Class
Convert Class – The .NET Framework has a static class available that can be used for converting values from one type to another. The System.Convertclass has some methods that can be used to convert to different target datatypes. You must import the System namespace before using the Convert class. Below shows the table of those methods
Command | Result |
---|---|
Convert.ToBoolean(val) | val converted to bool |
Convert.ToByte(val) | val converted to byte |
Convert.ToChar(val) | val converted to char |
Convert.ToDecimal(val) | val converted to decimal |
Convert.ToDouble(val) | val converted to double |
Convert.ToInt16(val) | val converted to short |
Convert.ToInt32(val) | val converted to int |
Convert.ToInt64(val) | val converted to long |
Convert.ToSByte(val) | val converted to ushort |
Convert.ToSingle(val) | val converted to float |
Convert.ToString(val) | val converted to string |
Convert.ToUInt16(val) | val converted to ushort |
Convert.ToUInt32(val) | val converted to uint |
Convert.ToUInt64(val) | val converted to ulong |
The following program shows you an example of converting variables.
double x = 9.99;
int convertedValue = Convert.ToInt32(x);
Console.WriteLine("Original value is: " + x);
Console.WriteLine("Converted value is: " + convertedValue);
Original value is: 9.99 Converted value is: 10
The value of val can be any data type but make sure that it can be converted to the target data type. If these commands cannot handle the conversion, then the compiler will tell you about this by issuing an error.
Subscribe
Login
0 Comments
Oldest