private void txtOctet1_TextChanged(object sender, EventArgs e)
{
double numCheck1;
if (txtOctet1.Text == "")
{
}
else
{
numCheck1 = Convert.ToDouble(txtOctet1.Text);
if (numCheck1 < 0 | numCheck1 > 255)
{
btnSubnetting.Enabled = false;
lblOctet1Error.Text = "Error";
lblOctet1Error.BackColor = Color.Red;
lblOctet1Error.ForeColor = Color.White;
}
else
{
btnSubnetting.Enabled = true;
lblOctet1Error.Text = "No Error";
lblOctet1Error.BackColor = Color.White;
lblOctet1Error.ForeColor = Color.Black;
}
}
}
I have made a decimal to binary converter in C#. This users a class made by me. The user enters their “IP address” in four textboxes (one for each Octet). The above code does work but I don’t want to have to repeat the above code for the other third Octet input textboxes. How would I manage this (if it is possible)
Instead of showing you the solution, let’s play with VS a bit :
1. Introduce two variables that hold the textbox and label references and replace all use below :
No progress for the moment
2. Select the code you want to reuse
with the mouse or the keyboard, select all code between the two comments place holder I’ve put. Basically, you should have wrapped up the outermost
if/elsestatement.3.a Extract to a method
Right click the select code, choose
Refactor,Extract to a method.Choose a name for your method, ValidateOctet for example.
Validate. You should have extracted the logic in a custom method :
Still no visible progress
3.b (Optionnal) remove useless variable
I choose to simplify the code by removing the variable we created before. I can call the method directly with the textbox and label reference. Choosing to keep the variable or not is a matter of code styling.
4. Reuse the method for all textboxes
Simply call
ValidateOctetfor all couple of Textbox/Label :Progress: you have now the logic defined in one place
5. Possible optimization
System.Net.IPAdressclass. That provides a set of methods to play with IP Addresses (notably theTryParsemethod).Disclaimer
Please not that my answer was not targeted to find the better solution, but help you with using Visual Studio and it’s refactoring features. It’s quite common to start with simple things, to prototype, or playing a bit before the actual implementation. Refactoring tools allows to simply redesign some parts of your code.