C# cast to int code example

Example 1: string to int c#

int x = Int32.Parse("1234");

Example 2: parsing string to int c#

string userInput = Console.ReadLine();
int convert;
Int32.TryParse(userInput, out convert);  // Converting String to int

Example 3: convert string to number C#

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Example 4: convert string to int c#

Int16.Parse("100"); // returns 100
Int16.Parse("(100)", NumberStyles.AllowParentheses); // returns -100

int.Parse("30,000", NumberStyles.AllowThousands, new CultureInfo("en-au"));// returns 30000
int.Parse("$ 10000", NumberStyles.AllowCurrencySymbol); //returns 100
int.Parse("-100", NumberStyles.AllowLeadingSign); // returns -100
int.Parse(" 100 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite); // returns 100

Int64.Parse("2147483649"); // returns 2147483649

Example 5: c# string to int

//Input must be numeric 0-9
string input = Console.ReadLine();

//Converts the string input to int
int X = int.Parse(input);

//Prints the X value
Console.WriteLine(X);

Example 6: c# type conversion

// --------------------- TYPE CONVERSION --------------------- //

// Implicit conversion
float varFloat = 12.7f;
double varDouble = varFloat;   // converts float => double


// Explicit conversion (casting)
double varDouble = 2.3;
int varInt = (int) varDouble;        // converts double => int


// Type convertion: number to string
int varInt = 19;
string varString = varInt.ToString();    // converts int => string


// Type convertion: string to number
string varString = "89";   
int varInt = int.Parse(varString);         // converts string => int
double varDouble = double.Parse(varString);  // converts string => double
//OR
int varInt = Convert.ToInt32(varString);
double varDouble = Convert.ToDouble(varString);