Convert Commands C#
The type of explicit conversion you have been using in many of the Try It Out examples is a bit different from those you have seen so far in these tutorials. You have been converting string values into numbers using commands such as Convert.ToDouble() , which is obviously something that won ’ t work for every possible string.
Convert | 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 sbyte |
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 |
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { short shortResult, shortVal = 4; int integerVal = 67; long longResult; float floatVal = 10.5F; double doubleResult, doubleVal = 99.999; string stringResult, stringVal = "17"; bool boolVal = true; Console.WriteLine("Variable Conversion Examples\n"); doubleResult = floatVal * shortVal; Console.WriteLine("Implicit, - > double: {0} * {1} - > {2}", floatVal, shortVal, doubleResult); shortResult = (short)floatVal; Console.WriteLine("Explicit, - > short: {0} - > {1}", floatVal, shortResult); stringResult = Convert.ToString(boolVal) + Convert.ToString(doubleVal); Console.WriteLine("Explicit, - > string: \"{0}\" + \"{1}\" - > {2}", boolVal, doubleVal, stringResult); longResult = integerVal + Convert.ToInt64(stringVal); Console.WriteLine("Mixed, - > long: {0} + {1} - > {2}", integerVal, stringVal, longResult); Console.ReadKey(); } } }