0

I already know you can't normally do this but here's my situation:

I have a non-static List<T> that gets added to during normal use, and then dumped to a database at an interval. I want to be able to use AppDomain.CurrentDomain.ProcessExit in order to dump any values in my List<T> that haven't been dumped yet. The List is cleared each time it is dumped.

Is there any way I can access this List without the given context even though it is static -> not-static?

5SK5
  • 159
  • 1
  • 1
  • 15
  • [No](http://programmers.stackexchange.com/questions/211137/why-can-static-methods-only-use-static-data). But if you can get access to the instance variables then you can access the data. Ultimately everything is within some context and with the right designs, methods, and APIs you can do what you are trying. – TheNorthWes Apr 18 '16 at 20:34
  • Make the handler non-static. – SLaks Apr 18 '16 at 20:34
  • @SLaks or make the list static. – RoadieRich Apr 18 '16 at 20:37

1 Answers1

1

Just add your handler as a lambda, in a scope where it has access to your list.

var list = new List<string>()
{
    "Item 1",
    "Item 2"
};

AppDomain.CurrentDomain.ProcessExit += (sender, theArgs) =>
{
    File.WriteAllLines(@"C:\temp\mylist.txt", list);
};

One nice way would be to encapsulate this behaviour inside a subclass of List<T>.

public class MyReallyPersistentList<T> : List<T>
{
    public MyReallyPersistentList()
    {
        AppDomain.CurrentDomain.ProcessExit += (sender, args) => 
        {
            var items = this.Select(i => i?.ToString());
            File.AppendAllLines(@"C:\temp\mylist.txt", items);
        };
    }
}
RB.
  • 36,301
  • 12
  • 91
  • 131
  • so i can set the handler for ProcessExit even though Application.Run() has already been executed? – 5SK5 Apr 18 '16 at 20:47
  • You never mentioned Application.Run before. Is this a WinForms application? I don't see why it would matter though - you can add a ProcessExit handler any time before your process exits (obviously not after!!) – RB. Apr 18 '16 at 20:49
  • Well, whatever you are using, you are aiming to add the ProcessExit handler just after you create the list. As I say, encapsulating this logic inside a subclass of `List` is the easiest and safest (and most self-documenting) way to do it. – RB. Apr 18 '16 at 20:51