Csharp/C Sharp/Data Types/Convert
Convert string to int
using System;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
Console.WriteLine("Enter an integer:");
int myInt = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Integer less than 10? {0}", myInt < 10);
Console.WriteLine("Integer between 0 and 5? {0}",
(0 <= myInt) && (myInt <= 5));
Console.WriteLine("Bitwise AND of Integer and 10 = {0}", myInt & 10);
}
}
Hidden among the To(integral-type) methods are overloads that parse numbers in another base:
using System;
public class MainClass {
public static void Main() {
int thirty = Convert.ToInt32("1E", 16); // parse in hexadecimal
uint five = Convert.ToUInt32("101", 2); // parse in binary
}
}
The source and target types must be one of the "base" types. ChangeType also accepts an optional IFormatProvider argument. Here"s an example:
using System;
public class MainClass {
public static void Main() {
Type targetType = typeof(int);
object source = "42";
object result = Convert.ChangeType(source, targetType);
Console.WriteLine(result); // 42
Console.WriteLine(result.GetType()); // System.Int32
}
}