Lachlan Mather Lachlan Mather - 1 year ago 88
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 Source

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


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download