Enrico Enrico - 1 year ago 167
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) {
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!)

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download