I have 2 forms, in the main one I create an instance of some class and process it in another, and when another form is closed, the class instance is destroyed. Is it possible to avoid destroying an instance of a class so that it can be reused in the main form?
-
1This question isn't about using the Visual Studio application, so I've removed that tag for you. Please ensure you read tag descriptions before using them. – ProgrammingLlama Nov 16 '21 at 04:32
-
2I recommend reading the answers to [Understanding garbage collection in .NET](https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net). A class instance is destroyed when it is garbage collected. This only happens to objects who have no references to them. The solution in your case: pass a reference to the instance to the main form. – ProgrammingLlama Nov 16 '21 at 04:34
1 Answers
This has nothing to do with Winforms. However, it has to do with garbage collection.
You'll have to understand, that as long as anyone holds a reference to an object, that object is not garbage collected (= what you call destroyed). In other words: if everyone has "forgotten" object X, then after a while, object X is garbage collected. This seems the right thing to do, because since no one has a reference to X, no one can do anything with this object anymore.
So you have an form A (your main form), which creates an object X. You also have a form B, and somehow, form B knows about object X. Probably Form A tells form B about object X.
Now there are two possibilities:
After form A informs form B about object X, form A does not need object X anymore: it has passed ownership to form B. Form B has to remember object X, and when form B is garbage collected, no one uses object X anymore, so object X is also garbage collected.
If form A still needs object X, after it has told form B about the existence of object X, form A may not forget object X, so form A must have a reference to object X. If form B is garbage collected, there is still someone with a reference to object X, so object X will not be garbage collected.
class FormA { public MyClass X {get;} = new MyClass();
...
}
class FormB { public MyClass X {get; set;} ... }
Someone (best guess: FormA) creates FormB and informs FormB about X:
private void ShowFormB()
{
using (FormB b = new FormB())
{
b.X = this.X;
DialogResult dlgResult = b.ShowDialog();
// if here, b has been shown, and closed, but still exists
if (dlgResult == DialogResult.OK)
{
// use properties of form b to see what the operator did
// process the result.
// note: b.X still has a value
}
// b.X still has a value
}
// here: there is no reference to b. If no one holds a reference to X
// then X is garbage collected.
// luckily form A still has reference to X in a.X, so X is not garbage collected

- 28,834
- 7
- 67
- 116