Praneet Nadkar
Praneet Nadkar

Reputation: 813

Better way to call methods based on conditions

I have a code snippet where I am calling my database and returning data in the form of DataReader. This is based on the params whether a stored proc is used to call or a plain text is used. Something like this:

IDataReader dataReader = null;

if (commandType == CommandType.StoredProcedure)
{
   dataReader = GetReaderByProc(proc, parameters);
}
else if (commandType == CommandType.Text)
{
   dataReader = GetReaderByText(text);
}

where commandType is System.Data.CommandType

Now this works absolutely fine. But I am curious, in such code scenarios is there a better way to implement this.

Can there be more elegant or a better way where I can call methods based on a condition?

Upvotes: 1

Views: 110

Answers (1)

peeyush singh
peeyush singh

Reputation: 1407

You can use a dictionary to hold the key (commandType) and value of different Func<> and then simply get the func using the key and execute it.

      public static Dictionary < string, Func<string, parameters, IDataReader> dbMethods = 
                           new Dictionary<string, Func<string, parameters, IDataReader>();

         public static void CreateMethodDictionary()
         {                
            dbMethods.Add(CommandType.StoredProcedure, GetReaderByProc);
            dbMethods.Add(CommandType.Text, GetReaderByText);
         }

And then you can invoke it like:

IDataReader dataReader = dbMethods[commandType].Invoke(proc, parameters);

This does assume that both your calling functions take in the same parameters (which is not the case currently) and return the same object.

Looking at the code though your text query should also take in parameters since parameterized queries should be the norm.

Upvotes: 1

Related Questions