Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an empty interface used for

Tags:

interface

I am looking at nServiceBus and came over this interface

namespace NServiceBus {     public interface IMessage     {     } } 

What is the use of an empty interface?

like image 412
terjetyl Avatar asked Dec 19 '08 11:12

terjetyl


People also ask

What is the use of empty interface in C#?

An empty interface does not define any members. Therefore, it does not define a contract that can be implemented. If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types.

What is an empty interface called?

An interface that does not contain methods, fields, and constants is known as marker interface. In other words, an empty interface is known as marker interface or tag interface.

What is the purpose of an interface?

The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.

Is an empty interface valid in Java?

Answer 4: Yes. Methods are not required. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.


2 Answers

Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.

This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.


@Stimpy77 Thanks! I hadn't thought of it that way. I hope you'll allow me to rephrase your comment in a more general way.

Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.

like image 149
Mendelt Avatar answered Sep 30 '22 23:09

Mendelt


Also known as a Marker Interface:

http://en.wikipedia.org/wiki/Marker_interface_pattern

like image 28
mattcole Avatar answered Sep 30 '22 22:09

mattcole