Lachlan Mather Lachlan Mather - 2 months ago 8
C# Question

C# for-loop declaring variables

In my WPF program, I have an area of C# code that is quite repetitive, and it looks like this:

labelFirst = EnglishPicker.SelectedColorText.Substring(0, 1);
labelLast = EnglishPicker.SelectedColorText.Substring(3, 6);
label = labelFirst + labelLast;
UpdateSetting("English", label);
labelFirst = PhotographyPicker.SelectedColorText.Substring(0, 1);
labelLast = PhotographyPicker.SelectedColorText.Substring(3, 6);
label = labelFirst + labelLast;
UpdateSetting("Photography", label);


So I had a thought, is it possible to put this in a for loop something like this:

string[] names = {"English","Photography"};
foreach (string name in names)
{
labelFirst = (name +"Picker").SelectedColorText.Substring(0, 1);
}


Thanks for any answers.

Answer

Instead of a reflection-based solution, I would simply refactor the code to move the shared code in a separate method.

Example:

SharedMethod(EnglishPicker, "English");
SharedMethod(PhotographyPicker, "Photography");

// ...

private void SharedMethod(PickerClass picker, string settingName)
{
    var labelFirst = picker.SelectedColorText.Substring(0, 1);
    var labelLast = picker.SelectedColorText.Substring(3, 6);
    var label = labelFirst + labelLast;
    UpdateSetting(settingName, label);
}
Comments