For me, the expected result was correct. You enter a type (possibly using it incorrectly) of a variable as IApple.
For instance:
IApple apple = new RottenApple(); apple.Eat(); // "Yummy, that was good!" IRottenApple apple2 = new RottenApple(); apple2.Eat(); // "Eat it yourself, you disgusting human, you!" var apple3 = new RottenApple(); apple.Eat(); // "Eat it yourself, you disgusting human, you!"
Question: What would be a refined / more accurate guide to using extension methods or virtual instances? When does using extension methods for "programming in an interface" go far? When are instance methods really needed?
Just my personal opinion when developing the application:
I use instance methods when I write something that I can or someone else can use. This is because it is a requirement for what type it really is. Consider the FlyingObject
interface / class using the Fly()
method. This is the basic fundamental method of a flying object. Creating an extension method really doesn't make sense.
I use (many) extension methods, but this is never a requirement for using the class they distribute. For example, I have an extension method to int
that creates a SqlParameter
(optionally, it is internal). However, it makes no sense to have this method as part of the int base class; it really has nothing to do with what int does or does. An extension method is a visually good way to create a reusable method that consumes a class / structure.
source share