Home > Blockchain >  Create a generic method to modify a reference list of unknown type
Create a generic method to modify a reference list of unknown type

Time:05-04

I have few database scripts that all contains a List of there own type.

Like the example below:

public class FooDatabase()
{
    public List<Bar> myCollection;
}

Than I have more database with the same format:

public class OtherDatabase()
{
    public List<OtherBar> myCollection;
}

The items in the List always have an int ID regardless of what type they are.

Now I'm looking to implement a generic method that takes the ref collection and do some operations on it. The problem is if I give them an interface than I can't modify the ref collection.

public static void FillDatabase<T>(ref List<T> collection, string folderName)
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    // I need to make changes to the ID field regardless of which collection and type is passed in
    // Can't do the following, because it doesn't know it has the field ID
    foundItems.Find(item => item.ID == 0);

}

I tried to change the list to one of type List<IDatabaseEntry> with the IDatabaseEntry containing the ID field and having every class from every database implement that interface. The problem is that than I can't modify the original collection reverenced because the original collection isn't of type List<IDatabaseEntry>

Appreciate any help pointing in the right direction.

CodePudding user response:

public static void FillDatabase<T>(ref List<T> collection, string folderName) where T : IDatabaseEntry
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    // I need to make changes to the ID field regardless of which collection and type is passed in
    // Can't do the following, because it doesn't know it has the field ID
    foundItems.Find(item => item.ID == 0);

}

Should fix your issue.

CodePudding user response:

Another approach - if you have types with different ID types or properties you can pass Func returning ID as one of the parameters:

public static void FillDatabase<T, TKey>(ref List<T> collection, 
    string folderName, 
    Func<T, TKey> idGetter)
{
    collection = new List<T>();

    List<T> foundItems = Resources.LoadAll(folderName, typeof(T)).ToList();

    foundItems.Find(item => idGetter(item) == default(TKey));
} 
  • Related