Run correct method based on file name (C#)

Viewed 102

I'm checking name of the file and return TRUE if it's correct:

bool name_FORD = file.Contains("FORD"); 
bool name_KIA  = file.Contains("KIA");  
bool name_BMW  = file.Contains("BMW");

Based on this I want to have switch and run correct method. But I confused how to correctly do it:

switch (true)
{
 case 1 name_FORD: 
              method1();
              break();
 case 2 name_KIA:
              method2();
              break();
 case 3 name_BMW:
              method3();
              break();
}
2 Answers

I suggest organizing all strings and corresponding methods as a Dictionary:

Dictionary<string, Action> myCars = new Dictionary<string, Action>() {
  {"FORD", method1}, // e.g. {"FORD", () => {Console.WriteLine("It's Ford!");}},
  { "KIA", method2},
  { "BMW", method3}, 
  //TODO: Put all the cars here
};

then we can put a simple loop:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value();                // we execute corresponding method pair.Value

    break; 
  }

Edit: In case we can have complex methods (e.g. method may want file and key parameters) we can change signature:

// Each action can have 2 parameters: key (e.g. "FORD") and file
Dictionary<string, Action<string, string>> myCars = 
  new Dictionary<string, Action<string, string>>() {
     {"FORD", (key, file) => {Console.Write($"{key} : {string.Concat(file.Take(100))}")}}, 
     { "KIA", (key, file) => {Console.Write($"It's {key}!")}},
     { "BMW", (key, file) => {/* Do nothing */}}, 
  //TODO: Put all the cars here
};

When executing in the loop, we should provide these parameters:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value(pair.Key, file); // we execute corresponding method pair.Value

    break; 
  }

You can use methods like variables in c# by assigning them to an Action:

public void KiaMethod(){
  Console.WriteLine("Kia");
}
public void BmwMethod(){
  Console.WriteLine("BMW");
}

Action method = null;
if(file.Contains("KIA"))
  method = KiaMethod;
else if(file.Contains("BMW"))
  method = BmwMethod;

method();

Though I really do favor the pattern in Keiran's answer because I'm not really seeing why you need this level of complexity

Related