Why doesn't C # allow access modifiers for destructors?

I made a simple class for a small project and decided to just add a destructor for quick impl instead of using it IDisposable, and I came across a compiler error whenever it has a destructor with an access modifier.

public class MyClass
{
    public ~MyClass()
    {
        // clean resources
    }
}

I tried public, private, secure and internal. It worked perfectly without access modifiers. Since this article shows that ~ the destructor is essentially syntactic sugar for the protected Finalize function, it seems strange to me that you cannot use at least the protected on the destructor. The article says: "Destructors cannot be called, they are called automatically." Is this behavior true?

In the end, I just used IDisposable, but I'm curious ... is there another reason why you can't put access modifiers in a destructor ?

+3
source share
4 answers

The domain of accessibility of a member declared in the source code consists of a set of all sections of the program text in which this element can be accessed.

The availability modifier modifies the contents of the availability domain.

An interesting fact about accessibility modifiers is that an accessibility modifier always makes an accessibility domain larger or keeps it the same size. The availability modifier never reduces the scope of availability.

, . .

, , . ( "" , ). , , .

; .

? ? , , - ?

Finalize

. 10.13. , "Finalize" ; , .

, , . , , , .

+16

, .

public , .. ..

. GC. GC.

, . , .

"-", , , .

+13

, , , " . ".

-, , .

+5

You must use a one-time template.

Complete / delete template in C #

0
source

Source: https://habr.com/ru/post/1735667/


All Articles