C#C
C#3y ago
Hugh

❔ ✅ Lifetime of variable referenced in Func<>

In some of my tests, I'm creating tables as I go, and then dropping the tables at the end of the test fixture.

I'm doing this by having a RegisterType function that looks like this:

private readonly List<Func<Task>> _dropTableFunctions = new();

private async Task<bool> RegisterType<T>(Database database) where T : EntityBase, new()
{
  async Task DropTableFunction()
  {
    await database.DropTable<T>();
  }

  _dropTableFunctions.Add(DropTableFunction);

  return await database.RegisterEntityType<T>();
}


And then in my TearDown function, I iterate over _dropTableFunctions and call each one.

My question here is not related to the database side of this, but is to ask whether I'm risking the Database objects having been destroyed by the time these functions are called? Are references from a function like this considered proper references to the variable, or should I also be storing reference to each
database
instance elsewhere to ensure that it is kept alive?
Was this page helpful?