Saturday, 15 November 2025

Can you override private methods in C#?

Overriding Private Methods in C#

No. In C#, private methods cannot be overridden because they are not visible to derived classes. A method must be accessible (protected/public) and marked as virtual, abstract, or override to support overriding.

Example (Not Allowed)

class Base {
    private void DoThing() { }
}

class Derived : Base {
    private void DoThing() { } 
}
    

Correct Way (Use protected + virtual)

class Base {
    protected virtual void DoThing() { }
}

class Derived : Base {
    protected override void DoThing() { }
}
    

If you need to override behavior, make the method protected and virtual.

No comments:

Post a Comment