10

I think you can and my colleage thinks you cannot!

2

3 Answers 3

56

You can't even declare private virtual methods. The only time it would make any sense at all would be if you had:

public class Outer
{
    private virtual void Foo() {}

    public class Nested : Outer
    {
        private override void Foo() {}
    }
}

... that's the only scenario in which a type has access to its parent's private members. However, this is still prohibited:

Test.cs(7,31): error CS0621: 'Outer.Nested.Foo()': virtual or abstract members cannot be private
Test.cs(3,26): error CS0621: 'Outer.Foo()': virtual or abstract members cannot be private

1
  • 2
    Another time it would make sense would be if a derived class could override a private virtual method in the base, and if that method (and that method alone) could call the base-class implementation. This would allow a base class to enforce a requirement that all calls to a particular base-class function must be bracketed by some code in the base class (e.g. if Dispose(Boolean) were private virtual, a non-virtual base-class Dispose could do an Interlocked.Exchange() to ensure Dispose(Boolean) was only called once.
    – supercat
    Mar 17, 2011 at 21:46
5

Your colleague is right. You can't declare private virtual methods because there's no point (since there'd be no way to override them)...

But you can override protected virtual methods.

5
  • 2
    Sure you could override them; see Jon's example. Mar 17, 2010 at 6:58
  • But even in Jon's example, the compiler won't allow it. Mar 17, 2010 at 12:35
  • 8
    My point is simply that your claim that "there would be no way to override them" is incorrect. There would be a way to override them. The reason private virtual methods are illegal is because the language design committee doesn't like them, not because they are logically inconsistent. Mar 17, 2010 at 23:25
  • Ah...that makes sense. I see what you'te saying and totally agree. Mar 18, 2010 at 1:54
  • Excuse me, but there's a LOT of point to private virtual methods; a derived class overriding base behaviour is one thing, a derived class CALLING a base method is another thing entirely. It is very much desirable to not have child-class implementers have the ability to mess up the call orders of critically-ordered methods, even if they are overridable.
    – karnage
    Feb 24, 2017 at 19:50
0

You won't fund your private method in your derivative class. So the virtual keyword has no sens in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.