Possible Duplicate:
What is the purpose of a marker interface?
Is it bad practice to create a completely empty interface such as:
public interface ISomething { }
There is a case where I would like to treat certain objects differently than others, but I don't require any new behavior.
Interfaces are meant to describe behavioral contracts. An empty interface doesn't describe any behavior - you're not defining any form of contract here. The design guidelines for interfaces specifically says: Avoid using marker interfaces (interfaces with no members).
Generally, yes. By definition, empty interfaces provide you nothing. They can be marker interfaces (generally evil), or aliases for another type (occasionally useful due to legacy code when renaming something).
In most cases, a final class is the best thing you can create. If a user doesn't like your class, they can simply choose not to use it. However, if you're building up a hierarchy of objects you should introduce an interface for every class.
Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.
I personally think that empty interfaces are not a good thing.
Interfaces are meant to describe behavioral contracts. An empty interface doesn't describe any behavior - you're not defining any form of contract here.
The design guidelines for interfaces specifically says:
Avoid using marker interfaces (interfaces with no members).
Custom attributes provide a way to mark a type. For more information about custom attributes, see Writing Custom Attributes. Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.
Have you considered using an attribute instead of an interface? That would usually be my approach. Admittedly it's slightly harder to test for the presence of an attribute than whether an object implements an interface, but it feels like a better fit in general.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With