I had an interesting problem today. I had a public class in my assembly called Session
. It was a public class, but it used a lot of internal stuff in the implementation. It went something like this:
{
(public methods and properties here)
private void HandleResponse(Response response) // Response class is internal
{
…
}
}
Later I needed to split it into two classes: MarketDataSession
and TradeSession
. They have a lot in common, but they need to handle responses slightly differently. I decided to keep shared functionality in Session
making it a base class. So, I modified Session like this:
{
(public methods and properties here)
protected virtual void HandleResponse(Response response) // Response class is internal
{
…
}
}
public class TradeSession : Session …
public class MarketDataSession : Session …
I immediately ran into trouble: inconsistent accessibility, Response
class is less accessible then method HandleResponse
. Indeed, HandleResponse
is now a protected method of a public class, so theoretically it can be overriden outside of the assembly.
I could make Session
an internal class, but public classes TradeSession
and MarketDataSession
are not allowed to derive from an internal class.
The only solution that allows me to keep Response
class internal is to mark HandleResponse
method as internal. This makes it invisible from outside of the assembly, but now it is wide open inside the assembly, which is also not so stellar.
There is another, rarely used access control option, protected internal
, but it actually means protected OR internal, i.e. the method is accessible to anyone inside the assembly and to derived classes outside of the assembly.
What I need here is protected AND internal: accessible only to derived classes within the same assembly. AFAIK, this option exists in IL and in C++/CLI as private protected
. Here’s a real example where it would be useful in C#.
Permalink
hi,
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I
was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful
for .Net community.
There is a good C# resource site, Have alook
http://www.csharptalk.com/2009/09/c-class.html
http://www.csharptalk.com
simi