'How to parse a string to integer?
I want to use the CalcEngine
library for doing mathematic calculations in textboxes. The following codes are a part of the whole project. Why is it giving an error? The error is in CE.Evaluate(textBoxTLA.Text).ToString()
. The error says:
Argument 2 should be passed by out keyword.
private void button1_Click(object sender, EventArgs e)
{
CalcEngine.CalcEngine CE = new CalcEngine.CalcEngine();
int.TryParse(textBoxTLA.Text, CE.Evaluate(textBoxTLA.Text).ToString());
}
Solution 1:[1]
TryParse
takes an integer as a second parameter, and you are supplying a String
.
It works like this (I don't know which string you want parsed, I assumed the evaluated one):
int target;
CalcEngine.CalcEngine CE = new CalcEngine.CalcEngine();
int.TryParse(CE.Evaluate(textBoxTLA.Text).ToString(), out target);
It is better to use Parse
though, so you can do correct error handling (plus the code will be more readable).
Also, you are doing a lot in one line, which makes it harder to debug, and to give clear messages to your user. For example, what if CE.Evaluate
fails?
Solution 2:[2]
TryParse recieves two parameters, the string you want to parse, and an out parameter that receives the output..
So say my string is textBoxTLA.Text
, I would parse it to int like this:
int myInt;
if(int.TryParse(textBoxTLA.Text, out myInt))
{
//Do whatever you need with calcEngine
}
It does this so it can return a bool value of whether or not it succeeded, so if you don't enter the if cause it was not able to parse the int. Make sure to use this and avoid errors and exceptions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |