.NET: Why aren't Private Abstract methods allowed?

26. February 2008

Sometimes when creating base objects you want to create methods that are overridable by object that inherit the base object, but keep the methods from being public. However, the compiler throws an exceptions when you try to define a method as "Private Abstract".

Why doesn't the compiler like "Private Abstract" methods?

The reason for this is Private methods can not be overriden. So, essentially the Abstract is useless if the method is Private.

How can I create a "Private" method that's able to be overriden?

Simple, you just declare the method as "Protected Abstract". Protected defines that the method is only accessible from within the class that declared it, and from within any derived class.

C#, vb.net ,

Comments

2/27/2008 5:47:46 PM #
I lol'd.

And its "protected abstract".  

Whoever asked the original question must be smacked.
2/27/2008 7:26:16 PM #
It may seem obvious to some, but I posted it because it seems that most .NET developers aren't the most familiar with the real differences between the Public, Private and Protected keywords.
Samuel
Samuel
1/30/2009 2:41:21 PM #
Since your post last year, I don't know if you got better information on the matter, but the answers you provide to the question are pretty easy and superficial...

The fact is that it is surprising for any experienced C++ developer to come to this limitation of C#. "Private" attribute means that a method/attribute can only be CALLED from the class where it is declared as such (private), but there is nothing in OO that says it cannot be specialized (therefore overridden) in inheriting classes. That is allowed in C++, so that is why the question is raised for C#... why is not the same concept allowed in .NET?

Declaring a method as "protected abstract" is probably the best workaround, I agree, but that's what it is "a workaround". The scope of a protected method remains not the same as of a private.

This article explains the NVI pattern and illustrate a good application context for private virtual methods:
http://www.gotw.ca/publications/mill18.htm
Samuel
Samuel
1/30/2009 2:43:05 PM #
Oh, and here is just a good finding of an article answering the question accurately:

http://en.csharp-online.net/CSharp_Canonical_Forms%E2%80%94NVI_Pattern

Smile

-Sam