© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
9 replies
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
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>();
}
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
_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
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
database
instance elsewhere to ensure that it is kept alive?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Determine what variable is being referenced
C#CC# / help
3y ago
✅ Use of Func as part of function definition
C#CC# / help
11mo ago
Exporting Func/Action?
C#CC# / help
3y ago
❔ Cannot find .dll in referenced project
C#CC# / help
3y ago