C# – Creating Common Interface for Classes with Different Members

cinheritanceobject-oriented

Don't know how to put it, But I'll try to be as clear as possible

I have a project in which I am creating lots of classes and those classes have some common properties and methods but those methods could have different code in them,

So I decided to make an interface so that I could inherit that in all classes and all classes would have same methods in them like insert, update, delete with different code inside those those methods but this trick flopped when I discovered that not all classes have same structure like some have insert method but not update and if I inherit interface I have to provide a public declaration for all members of that interface which I don't want.

Trick two I thought about abstract classes created one too but same problem all the abstract members has to be implemented with public.

So long story short

I want to create a common inheritable structure which would work as a non instance-able blue print for classes and could be inherited into lots of classes but in many classes I don't want to implement all of the members of that structure

NOTE : I can do no-op(empty methods that do nothing, or return a null, for example) as some guys suggested me but that ain't the solution I am looking for because those unnecessary members will be visible during intellisence and that's what i want to avoid.

How can I do that ?

Best Answer

One way to do this is have one interface with the three methods, and implement it in a few abstract classes (these would be the base classes for the full implementations).

These abstract classes would only implement methods that are not needed and would implement them as no-ops (empty methods that do nothing, or return a null, for example).

Your actual implementation classes would inherit from these abstract classes and only implement the needed subset of operations.


Another option is to adhere to ISP (Interface Segregation Principle) and have a number of interfaces - one for each behaviour needed.

Update:

This second option would suit the requirement to not have certain methods show up in IntelliSense. It does, however, mean that you would not be able to use a single inheritance tree, but segregate it (which, from your description of the model, is probably the correct solution).

Related Topic