In ASP.NET and C# I’ve ran across this before. Your class needs to implement interface ISomething
in order for something in the super class to supply something to you.
I can’t remember the details, as I ran across it quite a while ago, but it had something to do with session variables in ASP.NET C#. It was part of the .NET framework.
At first, I thought this practice was rather silly and could be more gracefully implemented. However now I’m finding myself implementing this in the architecture of a home-grown project I’m working on. Using reflection, I detect the toggle a behavior on or off based on if it implements ISomething. Just an empty interface with no methods at all.
What is the technical name for this and is it good practice?
Marker Interface
Is it good practice? Well, like many things some people love them and some people hate them. See the links in the Wikipedia article for discussion. Personally I think they are rarely useful. The presence of a marker is essentially only a Boolean. It seems preferable to me to define an interface that allows richer information flow and then to pass references using that actual type.
Are you thinking of accessing session state in an .ashx generic handler by implementing the (empty) IRequiresSessionState
interface?
I don’t know what the technical name for that is. Is it a good practice? Well, I’m not entirely sure why it wasn’t done using an attribute.
e.g. instead of:
public class MyGenericHandler : IHttpHandler, IRequiresSessionState
{
}
Doing:
[RequiresSessionState]
public class MyGenericHandler : IHttpHandler
{
}
That certainly seems more intuitive, and more in line with more recently implemented features in ASP.NET and the .NET framework.
1
It’s simple–it works with ordinary interfaces. It’s used in Java a lot, Java lacking all the bells and whistles of C#. If you use it, you shouldn’t even need reflection (unless “is” is part of reflection), just:
if (list is RandomAccess) element = list[1000000005];
else Consol.WriteLine( "You do not have enough time to wait." )
(The code’s C#, RandomAccess
is Java. I think.) It can be even simpler, as:
public int GetElement( RandomAccess list ) { ... }
which means you never even have to check for a linked list sneaking though.
And no technology beyond interfaces is needed. It is more of a Java-y thing than a .NET thing. Simple, graceful, clever, and a bit sneaky. Better? Don’t know.
2