Advertisement
Intermediate C# Programming, Access Modifiers in C#

Can destructors have access modifiers?

Short answer

No, destructors in C# cannot have any access modifiers applied to them, since they are called automatically by the garbage collector rather than being called directly by other code, meaning concepts like public or private accessibility simply do not apply to them.

Save C# Programming mock interview
Advertisement
AModel answer
No, destructors in C# cannot have any access modifiers applied to them, since they are called automatically by the garbage collector rather than being called directly by other code, meaning concepts like public or private accessibility simply do not apply to them. Attempting to add an access modifier to a destructor results in a compiler error, since the syntax for a destructor does not support one.
public class ResourceHolder {
    ~ResourceHolder() {  // no access modifier allowed here
        // cleanup logic
    }
}
Real-world example
A developer new to C# tries to mark a class's destructor as protected out of habit from other object oriented languages, and learns that C# destructors simply do not accept access modifiers of any kind.
Likely follow-ups
  • How does a destructor differ from a constructor in terms of syntax rules?
  • What is the recommended alternative to destructors for deterministic resource cleanup in C#?
Related topics