Home > Net >  Problem getting generic methods to work (setting T via type)
Problem getting generic methods to work (setting T via type)

Time:11-15

Okay so in my code I have two interfaces: ILookupable and ILookupTable. ILookupTable has a constraint - ILookupTable - and an IList property.

I then have a service that works with ILookupables. There's a method GetText(T container...) that has a constraint - ILookupable. In the GetText() method if the LookupTable in the container argument is empty it will call another method, GetLookupTable, where the constraint is for ILookupTable. This will query the DB to look for the necessary data and return it.

So what I want to do is have an instance of ILookupable, call GetText using it, and then use the ILookupable's ILookupTable to call GetLookupTable. But I can't get it to work. Is there a solution that doesn't involve reflection jank?

Essential parts of the code below:

public interface ILookupable<T> where T : ILookupTable {

        public int Id { get; set; }

        public IList<T> LookupTable { get; set; } = new List<T>();

}

public interface ILookupTable {

        public int RefId { get; set;}

        etc.

}

protected string GetText<T><T container, string lookup) where T : ILookupable<ILookupTable> {

        blah blah blah

        if (!container.LookupTable.Any())
                container.LookupTable = GetLookupTable<*type of lookup table*>(container.Id);

}

protected IList<T> GetLookupTable(int refId) where T : ILookupTable {

        blah blah return List<T>...

}

CodePudding user response:

If I'm correct your main concern is this line:

container.LookupTable = GetLookupTable<*type of lookup table*>(container.Id);

So you would like to do something like GetLookupTable<typeof(T)> ?

Sorry to break it to you: but can't be done like that. When using T in this manner the compiler needs to know the type (so it can be compiled), it cannot be set in run-time.

However there are options; First (would be my favorite) rewrite your interface the instance is required to fulfill your GetLookupTable (without the T - since the instance already "knows" the T). You could create an abstract base class which you also inherit so you don't need to write that method for all implementations.

Second would be (I would not recommend it) would be a giant "switch/factory-like" if T = "certain type" then GetLookupTable but it's error-prone and to be honest not desired.

  • Related