I have a method that takes an anonymous function parameter. This function’s parameter is provided by a local variable.
public void DoSomething<T>(Action<T> method) where T : new()
{
T instance = new T();
method.Invoke(instance);
}
I want to prevent creating a closure. Local variable should go out of scope when DoSomething<T> is finished. Is there a way to constrain it at compile time?
Here’s the situation I want to avoid:
Foo capturedInstance = null;
DoSomething<Foo>(item => capturedInstance = item);
capturedInstance.Call();
Unfortunately*, that’s not possible. You have little to no control over what a method does with its arguments. It would be possible to work around if you weren’t using generic types, but you are, so just don’t worry about that kind of situation. (I hope you don’t have to.)
* Actually, I consider it “fortunately”. This isn’t C++ we’re talking about here.