What\'s the proper way to pass a ComboBox Selected Item as a Method Parameter?
Or is there even any advantage to doing this?
I have limited experience in program
To get the Selected Item's string you need to call ToString(). Then you can pass the string to any method instead of an object. That being said, you can create a Dictionary to easily get the opposite color using the selected item's name instead of using if/else or switch statements:
private static Dictionary _oppositesDictionary = new Dictionary()
{
{"Green", "Red"},
{"Orange", "Blue"},
{"Yellow", "Purple"},
{"Red", "Green"},
{"Blue", "Orange"},
{"Purple", "Yellow"}
};
public string OppositeColor(string color)
{
//No need to check if key exists
return _oppositesDictionary[color];
}
private void button_Click(object sender, RoutedEventArgs e)
{
string color = cboColors.SelectedItem.ToString();
MessageBox.Show(OppositeColor(color));
}
If you want to perform small tasks based on the color name, use a switch statement.
If you want to perform different tasks (no repeating code!) based on the color name, you might want to create a Dictionary or Dictionary if you want to return a value.
Because you have only shown us an example of what you want, I can only think that this is an overkill:
//Methods have to be static when using a field initializer
//Func returns a string and has no paramters
private static Dictionary> _colorFunc = new Dictionary>()
{
{"Green", GreenFunc},
{"Orange", BlueFunc}
....
};
private static string GreenFunc()
{
// green logic
return "Red";
}
//Usage
public string OppositeColor(string color)
{
return _colorFunc[color]();
}