first question here, so hopefully you’ll all go gently on me!
I’ve been reading an awful lot over the past few days about polymorphism, and trying to apply it to what I do in c#, and it seems there are a few different ways to implement it. I hope I’ve gotten a handle on this, but I’d be delighted even if I haven’t for clarification.
From what I can see, I’ve got 3 options:
- I can just inherit from a base
class and use the keyword
‘virtual‘ on any methods that I
want my derived classes to
override. - I could implement an abstract class with virtual methods
and do it that way, - I could use an interface?
From what I can see, if I don’t require any implementation logic in the base, then an interface gives me the most flexibility (as I’m then not limiting myself with regards multiple inheritance etc.), but if I require the base to be able to do something on top of whatever the derived classes are doing, then going with either 1 or 2 would be the better solution?
Thanks for any input on this guys – I have read so much this weekend, both on this site and elsewhere, and I think I understand the approaches now, yet I just want to clarify in a language specific way if I’m on the right track. Hopefully also I’ve tagged this correctly.
Cheers,
Terry
An interface offers the most abstraction; you aren’t tied to any specific implementation (useful if the implementation must, for other reasons, have a different base class).
For true polymorphism,
virtualis a must; polymorphism is most commonly associated with type subclassing…You can of course mix the two:
abstractis a separate matter; the choice ofabstractis really: can it be sensibly defined by the base-class? If there is there no default implementation, it must beabstract.A common base-class can be useful when there is a lot of implementation details that are common, and it would be pointless to duplicate purely by interface; but interestingly – if the implementation will never vary per implementation, extension methods provide a useful way of exposing this on an
interface(so that each implementation doesn’t have to do it):