Is there any way that I can create a method that might have a different call and return parameter object?

Viewed 90

I am using this type of code:

lock (l)
{
   try
   {
      var data = db2.Query<CardSetWithWordCount>(qry);
      return data;
   }
   catch (Exception ex)
   {
      db2.Rollback();
      Debug.WriteLine(ex);
      Console.WriteLine(qry);
      throw;
   }
}

or another example like this:

lock (l)
{
   try
   {
      var data = db2.Query<CardSetDetails>(qry);
      return data;
   }
   catch (Exception ex)
   {
      db2.Rollback();
      Debug.WriteLine(ex);
      Console.WriteLine(qry);
      throw;
   }
}

The code is exactly the same except for the different objects that are the return type of db2.Query.

As it takes many lines I would like to replace these two blocks with a single method that I call and pass in the return object and a try string. But I am not sure where to start because the object returned which is in this case:

  <CardSetWithWordCount>

could be different (such as )for each method I would like to replace.

Is the way that I could do this in a method and if so how would I declare the parameters?

2 Answers

You can use generics like this:

T RunQuery<T>(YourDB db, string qry)
{

   lock (l)
   {
       try
       {
           T data = db.Query<T>(qry);
           return data;
       }
       catch (Exception ex)
       {
          db.Rollback();
          Debug.WriteLine(ex);
          Console.WriteLine(qry);
          throw;
       }
    }
 }

Call it like this:

YourType res=RunQuery<YourType>(db2,qry);

pleas look hier for more info: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

Pass in a Type parameter as a function param, then do your db2.Query passing in the type.

Related