C-SHARP - 2.6 conversion
To convert a string into an int in C#, the string must contain strictly a whole number. If the variable holds a number mixed with letters or any other character, the conversion is impossible - you can't turn letters into a number.
Converting a string to an int
Start from a string variable that holds a number:
string test = "30";
To convert it, create a variable of the target type and use int.Parse(), passing in the string to convert:
int conversion = int.Parse(test);
Console.WriteLine(conversion); // 30
Once converted, the value is treated as a real number and can be used in arithmetic:
conversion = conversion + 1;
Console.WriteLine(conversion); // 31
If the string contains anything other than digits - for example "30Hello" - int.Parse() fails, because it can't convert letters into a number.
Why this matters
In an earlier lesson, adding + 1 to whatever the user typed just appended it as text: the input function that reads user input always returns a string, whether the user typed a number or not. The program doesn't know in advance what that input represents, so it treats + 1 as string concatenation unless you explicitly convert first. This behavior is specific to how C# handles types - some languages, like Python, refuse outright to add a number to a string rather than silently concatenating it.