views:

315

answers:

4

What is the point of writing an interface without members ?

INamingContainer is one example in .NET Framework. And it's described in MSDN as :

Identifies a container control that creates a new ID namespace within a Page object's control hierarchy. This is a marker interface only.

Is it used for just this kind of blocks :

if (myControl is INamingContainer)
{
    // do something
}

Or are there other advantages of it ?

EDIT : It was called Marker Interface Pattern (thanks Preet)

+8  A: 

This is to ensure that you can treat a collection of objects as the same type and then perform some operations on that type (You know that it must inherit from object).

Think of it like attributes. It's type meta data.

You also might want to perform an operation on a known type (e.g. System.Web.UI.Control) but only perform that operation if the type inherits from a certain interface (e.g. INamingContainer).

foreach(var ctrl in this.Controls)
{
    if (ctrl is INamingContainer)
    {
        // Do something on the control
    }
}
Jonathan Parker
As a matter of fact, this is how I apply "attributes" in C++, since you don't have reflection but you do have RTTI.
Dave Van den Eynde
excellent point - not having done c++ for nearly 8 years I forget about things like this.
Preet Sangha
This doesn't seem like an answer the question. He asked about memberless interfaces -- ones that have no common operations or properties. It got accepted, tho...
Steve Cooper
The interface doesn't have a common operation but you still might perform a common operation *ON* types of that interface.
Jonathan Parker
+7  A: 

Memberless interfaces are used to provide mixin-like capabilities in C#. So given a class A:

class A : B { ... }

You can give it extra functionality (a-la multiple inheritance) by defining an interface IStuff:

interface IStuff {}

then 'implementing' it in A:

class A : B, IStuff { ... }

and then adding the extra features

class Methods {
  public static void Something(this IStuff stuff) {
    // some functionality here
  }
}
Dmitri Nesteruk
_very_ nice thought. Hadn't seen this possibility before, but will now look for opportunities.
Steve Cooper
very good idea!
Preet Sangha
+6  A: 

Its a marker interface. It can be used to decorate types so that you can find out it the type is correct at run time with out using reflection. we use it to ensure that generic types are correct in the callee.

Preet Sangha
Good point about the advantage of not using Reflection.
Dave Van den Eynde
Reflection has a significant performance hit.
Jonathan Parker
+3  A: 

To confuse pythonistas who think duck typing is cool.

Pete Kirkham
+1 funny (LOL for the kids).
kenny