I think you can and my colleage thinks you cannot!
Asked
Active
Viewed 2.3k times
10
-
15What about just trying? Every Windows system nowadays has a C# compiler ... – Joey Mar 16 '10 at 16:35
-
**Related:** [Why are private virtual methods illegal in C#?](http://stackoverflow.com/q/3082310/1497596) – DavidRR Jul 02 '14 at 12:46
3 Answers
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

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
2Another 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 '11 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.

Justin Niessner
- 242,243
- 40
- 408
- 536
-
2
-
-
8My 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. – Eric Lippert Mar 17 '10 at 23:25
-
Ah...that makes sense. I see what you'te saying and totally agree. – Justin Niessner Mar 18 '10 at 01: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 '17 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.

Lightness Races in Orbit
- 378,754
- 76
- 643
- 1,055

Stephane Halimi
- 408
- 3
- 5