Saeed mohammadi
Saeed mohammadi

Reputation: 319

How to define fixed parts of interface members

This is my interface :

Public Interface IProductComputer 
   Sub CalculatePrice
   Sub CalculateTax
   Sub Calculate
End Interface

And here are my classes :

Public Class Product1 
       Implements IProductComputer
     ........
End Class

Public Class Product2
       Implements IProductComputer
    ......
End Class

Problem :

My interface can be used in an unlimited number of classes and of course it should be implemented in all of them separately. But what if there are some common parts in an method?. For example there may be a common formula in CalculateTax method and it does not seem very pleasant to include this formula in all implementations (Instead implementing this formula in interface and implementing uncommon parts in classes which implements interface).

I've seen some .Net predefined interfaces which have some fixed parts like IDisposable (It has some kind of primary implementation when you implement it). Is there any approach to create an interface like them?

(above code is written in Vb.Net but I know C# syntaxes too) Let me explain more if I'm not clear enough.

Upvotes: 2

Views: 104

Answers (2)

David
David

Reputation: 10708

The simple answer to your question is no: Interfaces cannot contain code, there is simply an accepted pattern for IDisposable which is implemented many times over.

However, there are a couple of ways around this

  • You can implement and abstract class instead of an interface. You lose some of the implementation ability, since it's now a class and thus implementations cannot inherit from a different class. However, this is considered the primary difference between interfaces and abstract classes - code
  • It IS possible to write extension methods which target interfaces, allowing you use common code for certain common operations. This, however, becomes very limited since extension methods will only be able to access interface memebers, and are static and thus cannot be overidden in any way. While you could rewrite a method with the same name in a derived class, any compilation which targets the extension method will continue to target that extension method regardless.

Upvotes: 1

Brian Ball
Brian Ball

Reputation: 12606

By definition, an interface cannot have any methods/properties implemented, they can only be defined. You have two options to work around this:

  1. Change your implementation from an interface to an abstract class (I believe that is MustInherit in VB.net). Abstract classes can have some members implemented, while other members are only defined.

  2. Leave it as an interface, and if you have methods that you already have an implementation for, you can implement them as extension methods for your interface.

Neither of these solutions may be perfect for you, but hopefully one will be well-suited enough to your needs.

Upvotes: 2

Related Questions