Reputation: 319
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
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
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 - codeUpvotes: 1
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:
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.
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