I'm trying to avoid having to write a large number of switch/case (or if/else) statements in one area of my code. Take the following 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 ton of tables, I'm not too familiar with generics but I thought 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);
}
This seems to be ok, it doesn't give me any compiler errors, but my issue is I can't seem to 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 like a 'type'.
So I guess generics have to be identified at compile time. So I would have to have a massive switch/case or if/else statement to figure out the type anyway.
Can someone direct me towards an elegant way to do this? Or is there no way around it?