Creating an Integer
Most of the time, input from the user is collected via a textbox, say txtInput. The string data in the textbox is then converted to an integer using one of C# conversion methods. While several are possible, TryParse() can catch many errors without your own exception handlers. A code fragment might be:
bool errorFlag;
int myInteger;
flag = int.TryParse(txtInput.Text, out myInteger);
if (flag == false)
{
MessageBox.Show("Input error: Likely a non-digit input", "Input Error");
txtInput.Focus(); // Assumes you want them to try again.
return;
}
TryParse() accepts the input string from the textbox as input, but also sends the memory location (lvalue) of the integer you're trying to create (myInteger) as the second argument. If the conversion is successful, flag equals true. If an integer cannot be formed from the input, flag is false. The keyword out tells the code to send the memory location (lvalue) of myInteger rather than a copy of it's current value (rvalue). The compiler then knows where to put the converted data when the routine finishes, so myInteger will contain the converted integer if flag is true.
I hope this helps.
Dr. Purdum
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|