Reuse code between methods called multiple types

I am trying to avoid having to write a large number of switch / case (or if / else) statements in one area of ​​my code. Follow the next method:

async internal static Task UndeleteAsync(JObject item, string tableName)
{
    switch (tableName)
    {
        case "QuoteTask":
               var obj = item.ToObject<QuoteTask>();
               var deletedObj = (await MobileService.GetTable<QuoteTask>().IncludeDeleted().Where(x => x.Id == obj.Id).ToListAsync()).FirstOrDefault();
               await MobileService.GetTable<QuoteTask>().UndeleteAsync(deletedObj);                        
        break;
               //Only 26 more tables to go...                
    }        
}

      

This works well, but I have a lot of tables, I am not too familiar with generics, but I thought that maybe something like this would work:

async internal static Task UndeleteAsync<T>(JObject item)
{            
    var obj = item.ToObject<T>();
    var deletedObj = (await MobileService.GetTable<T>().IncludeDeleted().Where(x => (x as BaseObject).Id == (obj as BaseObject).Id).ToListAsync()).FirstOrDefault();
    await MobileService.GetTable<T>().UndeleteAsync(deletedObj);
}

      

Everything seems to be fine, it doesn't give me any compiler errors, but my problem is that I can't call it:

Type tableType = Type.GetType(operation.Table.TableName);
await AzureMobileServices.UndeleteAsync<tableType>(operation.Item);

      

I get the error "tableType" is a variable but is used as "type".

So, I think it is necessary to identify generics at compile time. So I would have to have a massive / case or if / else key to figure out the type anyway.

Can anyone guide me to an elegant way to do this? Or is there no way around it?

+3


source to share





All Articles