int.TryParse
I had a situation where I had to use int.TryParse. A field in the form that I will show later uses this method to convert a string value to integer. I want to ensure that the value is correct.
set
{
int intValue = 0;
//If not an integer value, throw an exception
if (!int.TryParse(this.txtReoccurrenceUnit.Text, out intValue))
throw new ArgumentException("The unit value is not of the right type", "value");
this.txtReoccurrenceUnit.Text = intValue.ToString();
}
So I whipped up a test to remove the possibility of a bug. I created the following test, which worked successfully. I was glad to find out that on the test "11X", TryParse evalutated to false, instead of removing faulty characters.
[Test()]
public void TestIntTryParse()
{
string value = "12";
int intValue = -1;
Assert.IsTrue(int.TryParse(value, out intValue));
value = "11X";
intValue = -1;
Assert.IsFalse(int.TryParse(value, out intValue));
value = "XXXY";
intValue = -1;
Assert.IsFalse(int.TryParse(value, out intValue));
}
But what about "11X", would it return 11, or -1 for no value? I thought I read that was the case, so I add three more asserts to the test, to go along with the existing asserts:
Assert.AreEqual(12, intValue);
Assert.AreEqual(11, intValue);
Assert.AreEqual(-1, intValue);
The second test failed; the value was zero instead of eleven, so my test was wrong. I correct the second test, changing 11 to 0, and see if the third test works. It does not; it seems no value is 0, not -1, and so I correct that also, to get a green bar.