Here is my method:
private void ConvertValues()
{
txtResult.Text = angles[cmbUnits1.SelectedIndex];
double value1 = Convert.ToDouble(txtValue1.Text);
double value2 = Convert.ToDouble(txtValue2.Text);
int unit1 = cmbUnits1.SelectedIndex;
}
What I want the method to do is to get the selected of the ComboBoxes and test the values. But I want to know if there is an alternative to this:
if( angles[cmbUnits1.SelectedIndex].Equals("Degrees") &&
angles[cmbUnits2.SelectedIndex].Equals("Radians")) {
...
}
By the way, I’m making a kind of unit converter so I will have sections other than angles. So I would like some enum, interface, abstract class, or class that I can implement. Maybe a class with the name Unit? So I can create new objects like Unit degrees = new Unit(Units.Angle) with Units as an enum. Or just Unit sqrMillimeters = new Unit("Area");?
Sure, polymorphism. Anytime you see long switch statements or if/then/else constructs it’s always possible to handle them using polymorphism and factories. In your case I’d imagine an ITemperatureConverter interface with concrete implementations for Fahrenheit, Celcius, Kelvin, and Rankine would do nicely.
UPDATE:
If you find you have this logic repeated, why not have a better abstraction for an Angle than a double?
If you’re writing in an object-oriented language, it’s a good idea to rise above primitives (e.g, double and, yes, string) to encapsulate behavior into objects.
I’d think about an Angle class that would hang onto the value and return it as whatever measure you wanted.
Here’s one way to do it in Java. I’ll leave the translation to C# and the rest for you.