DooDoo
DooDoo

Reputation: 13447

Refactoring switch cases

Please consider this psudo code:

switch (ddlPlan.SelectedValue)
{
    #region 02
       case "2":
           BL_02 bl_02 = new BL_02();
           bl_02.DeleteQues(Id, Version);
           break;
    #endregion

    #region 0503
       case "3":
           BL_03 bl_03 = new BL_03();
           bl_03.DeleteQues(Id, Version);
           break;
    #endregion

    #region 0505
       case "5":
           BL_05 bl_05 = new BL_05();
           bl_05.DeleteQues(Id, Version);
           break;
    #endregion
}

How I can refactor this code to remove this switch cases?

Much of my problem is how to get instance of BLs in appropriate way.

thanks

Upvotes: 1

Views: 1944

Answers (2)

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Assuming each class is a child of BL_Parent, you can use reflection to dynamically instantiate the class from a string value.

var className = String.format("BL_{0,2}", ddlPlan.SelectedValue);

var blObj = (BL_Parent)Activator.CreateInstance(null, className);

blObj.DeleteQues(Id, Version);

If you only want a certain set of numbers available, you can white list them like so.

var whitelist = new string[] { "2", "3", "5" };

if (!whitelist.Contains(ddlPlan.SelectedValue))
    // handle exception

You can find more information about Activator.CreateInstance() here.

Also, I suggest you re-factor your class structures, because judging by the naming conventions, there are better ways of handling data like this.

Upvotes: 3

itsme86
itsme86

Reputation: 19496

What about something like this?

Put this somewhere and then make your BL classes implement it:

public interface IBL
{
    void DeleteQues(string id, string version); // Assuming these are strings
}

Then rewrite your switch statement like this:

IBL bl;
switch (ddlPlan.SelectedValue)
{
    case "2": bl = new BL_02(); break;
    case "3": bl = new BL_03(); break;
    case "5": bl = new BL_05(); break;
}

bl.DeleteQues(Id, Version);

Alternatively, you could create a Dictionary<string, Type> instead of using a switch:

Dictionary<string, Type> blTypes = new Dictionary<string, Type>
    {
       { "2", typeof(BL_02) },
       { "3", typeof(BL_03) },
       { "5", typeof(BL_05) }
    }

And then instead of using switch you'd just do:

IBL bl = (IBL)Activator.CreateInstance(blTypes[ddlPlan.SelectedValue]);  // Could check if key exists
bl.DeleteQues(Id, Version);

Or, if you really wanted to get fancy and make it scalable, you could use reflection to generate the name of the class you want to instantiate.

Upvotes: 3

Related Questions