Well, thereโs one way you could do this - only allow access to your object through the static method that the delegate accepts. As a very simplified example (since, obviously, there are many different ways to open a file - read / write, etc.):
public static void WorkWithFile(string filename, Action<FileStream> action) { using (FileStream stream = File.OpenRead(filename)) { action(stream); } }
If the only things that can instantiate your one-time object are methods in your own class, you can make sure that they are used appropriately. Admittedly, nothing prevents the delegate from taking a copy of the link and trying to use it later, but this is not exactly the same problem.
This method severely limits what you can do with your object, of course, but in some cases it can be useful.
Jon skeet
source share