Reputation: 2731
I have a variable var1
. In the current context, it is pulled from the database and will be one of those values:
2, 6, 7 6t, 7q, 8q,
The number will only ever be single digit.
The number will only ever be the first characters in the variable.
I would like to create a single character variable (the number) from the variable I have put in.
Here for instance my variable Fac1Raw
has the value of 3c and I have tried to use this code:
var Fac1 = (int)(Fac1Raw.ToString().Substring(0, 1));
However I can't get it to work. Any ideas?
Upvotes: 1
Views: 1939
Reputation: 66389
You can't convert String to integer type directly. For this, you have the Parse methods. If you know for sure the string won't be empty and first character is a digit, you can parse without catching errors:
var Fac1 = Int32.Parse(Fac1Raw.ToString().Substring(0, 1));
If you do want some validations to prevent your code from crashing:
string rawFac1 = Fac1Raw.ToString();
if (rawFac1.Length == 0 || !char.IsDigit(rawFac1[0]))
{
//handle invalid value
}
else
{
var Fac1 = Int32.Parse(rawFac1[0].ToString());
//...rest of code
}
Upvotes: 1