Enrico Enrico - 3 months ago 12
C# Question

C# generic T function where T is from a string

I'm creating a synchronize function between a device and server for a large database. I have a lot of listing tables (the items in a dropdown/picker).
I don't want to write a lot of code and I'm looking for an elegant solution :)

On a device in SQLite I defined listing table like

public class NameTable : IBusinessEntity {
public int Id { get; set; } = 0;
public string Description { get; set; }
}


When I save in database a new record (item) I call this function

public int SaveItem<T>(T item) where T : IBusinessEntity {
lock (locker) {
if (item.Id != 0) {
database.Update(item);
return item.Id;
}
else {
return database.Insert(item);
}
}
}


Now when the device receives a new record from the server the structure is like

public class SyncResult {
public int DeviceId { get; set; }
public int ServerId { get; set; }
public string TableName { get; set; }
public string Description { get; set; }
}


Then I want to save (insert a new record if DeviceId == 0 or update an existing item).

My question is: how can I call SaveItem where T is the TableName from SyncResult?

Thank you in advance for any help (I can offer a beer for that!)




SaveItem
is a member of
MyDatabase
class. Basically my problem is how to pass to
SaveItem<T>
the T as string.

I don't know if I explained clearly my issue.

Answer

You could map a TableName to a Type for example Dictionary<string,Type> Use the Activator class to construct the type. Use reflection to fill the data.