Search:

Custom Search
_________________________________________________________________

Tuesday, March 25, 2008

Converting String to Int (C# .NET)


Here I will show you some easy ways you can convert String to integer in C#. The first way is by using the System namespace of the .NET Framework Class Library. In this namespace you can find the "Convert" class that lets you convert a base type to another base type.
Example:

String num = "123";

//First argument the String and second the base.
int a = System.Convert.ToInt32(num, 10);

Another way is by using the Parse function.
Example:

int b = Int32.Parse(num);

Now, if you want a method for doing these convertions, you can take a look at the following example. For argument the String value to be converted and return the integer for it. To make it a little interesting, the String value contains non numeric characters until the position number 6, example: abbton4457

public int change(String s) {
String st = s.Substring(6);
int x = Int16.Parse(st);
return x;
}



No comments: