C# FAQ: How do destructors work in CSharp?
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
How do destructors work in C#?
A destructor is a method that is called when an object is destroyed—it's memory is marked unused. C++ destructors are used to free up memory and other resources and to perform housekeeping tasks. In .NET, the Garbage Collector (GC) performs much of this type of work automatically. Generally, rather than define a destructor for manual cleanup, let the Common Language Runtime (CLR) handle it.
In C#, the Finalize method performs the operations that a standard C++ destructor might perform. Finalizers are similar to destructors except that it is not guranteed that they will be called by the CLR.
Here is a sample finalizer specification using the C++ destructor syntax which places a tilde (~) symbol before the class name:
class Test { ~Test() { ... } public static void Main() {} }
When defining a C# finalizer, it is not named Finalize. However, finalizers do override object.Finalize(), which is called during the garbage collection process.
See also
- Classes, Structs, and Objects—Finalizers
- ECMA-334: 8.7.9 Finalizers
- Are C# constructors inherited?
- How can one constructor call another?
- Are constructors the same in C++ and C#?
- Are destructors the same in C++ and C#?
- How call a virtual method from a constructor or destructor?
- How do destructors work in C#?
- How enforce constructor correctness in C#?
- How make a C# destructor virtual?
- What are the differences between C# and Java constructors?
- What are the differences between C# finalizers and Java destructors?
- What is the syntax for calling an overloaded constructor from within a constructor?
- Why must
structconstructors have at least one argument?