-1

I have this code:

   void openPicker(object sender, EventArgs e) {
        if (sender != null)
        {
            var a = sender;
            Picker pkr = sender == ati ? atiPicker : ptiPicker;
            pkr.Focus();
        }
    }

The code works good but I need to be able to assign pkr to one of:

atiPicker, ptiPiker, noaPicker prtPicker cfsPicker coPicker 

based on the sender being one of

ati, pti, not, prt, cfs or co

I think I could do it with many if statements but is there some way that would be better to do this?

4
  • 2
    Use a Dictionary.
    – mjwills
    Aug 3, 2017 at 13:18
  • Use a Dictionary and switch on ati, pti, not, prt, cfs or co (Expanding on @mjwills)
    – Ubernator
    Aug 3, 2017 at 13:19
  • Can you show and example. Thanks
    – Alan2
    Aug 3, 2017 at 13:22
  • What is ati? Be aware that depending on that type your == may check for reference-equality, making two instances of a class unequal even if all their properties are equal. Aug 3, 2017 at 13:33

3 Answers 3

1
void openPicker(object sender, EventArgs e) {
     if (sender != null)
     {
         var a = sender;
         Picker pkr = sender == ati ? atiPicker : ptiPicker;
         pkr.Focus();
     }
}

could be changed to:

Dictionary<object, Picker> bob = new Dictionary<object, Picker>() { { ati, atiPicker}, { pti, ptiPicker }};

void openPicker(object sender, EventArgs e) {
     if (sender != null)          
     {
         var a = sender;
         Picker pkr = bob[sender];
         pkr.Focus();
     }
}

The Dictionary allows you to codify the if statements into a hash lookup instead.

1

Try a switch statement

Picker pkr = new Picker();

switch(sender){
    case ati:
        pkr = atiPicker;
        break;
    case pti:
        pkr = ptiPicker;
        break;
    case noa:
        pkr = noaPicker;
        break;
    case prt:
        pkr = prtPicker;
        break;
    case cfs:
        pkr = cfsPicker;
        break;
    case co:
        pkr = coPicker;
        break;
}

pkr.Focus();
1

As mentioned in the comments you may use a Dictionary<Type, Func<Picker>>:

var map = new Dictionary<Type, Func<Picker>> { 
    { typeof(ati) }, () => new ATI_Kicker() }, 
    { /* other types */ }}

Now you can easily create instances by accessing the value for a given type of sender:

var picker = map[sender.GetType()]();
picker.Focus();

However this allways returns a new instance of the type attached to any of your sender-types every time you query the value for a given key in that map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.