Convert String to Another Datatype in C#

Updated on     Kisan Patel

If you have a string and you want to convert this string to its equivalent value type then you need to use Parse static method of the type that the string is to be converted to.

To convert a string containing a number to its numeric type:

string longString = "12345";
int actualInt = Int32.Parse(longString); // longString = 1234

To convert string to a double type:

Namespace:

System.Globalization

Code:

string dblString = "-4321.123";
double actualDbl = Double.Parse(dblString, NumberStyles.AllowDecimalPoint | 
                                                         NumberStyles.AllowLeadingSign); // dblString = "-4321.123"

To convert a string containing a Boolean value to a bool type:

string boolString = "true";
bool actualBool = Boolean.Parse(boolString); // actualBool = true

To convert a string containing a char value to a char type:

string charString = "t";
char actualChar = char.Parse(charString); // actualChar = 't'

C#

Leave a Reply