In what scenarios would somebody pass (or receive) an interface as a parameter? Is it really a useful thing or just a fancy way of doing something?
In what scenarios would somebody pass (or receive) an interface as a parameter? Is
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s an extremely useful thing.
Take any of the LINQ extension methods, for instance. They don’t care what’s passed to them, as long as it implements
IEnumerable<T>. The idea is that they can all be applied to anything that you can enumerate over using aforeachloop.Imagine how pointlessly restrictive it would be if they all required you to pass
T[]arrays, orList<T>objects, for example.Here’s just one very trivial illustration. Let’s pretend the LINQ extensions don’t exist (which is actually a real possibility if I’m using .NET 2.0) and I want to write a
Summethod.I could write it like this:
That’s all well and good, but notice something here: I wrote the method to take a
List<double>, which is a class that has far more functionality than this code depends on. Where does it useInsert? Where does it useRemoveAt?FindAll?Sort? Nope, none of that is required. So is it really necessary that this method get passed aList<double>?Moreover, say I have a
double[]. Theoretically, I should be able to pop that right in as thevaluesparameter, since all I’m doing is enumerating over it using aforeach; but since I’ve typedvaluesasList<double>, to pass adouble[]to mySummethod I’d have to do this:That’s just a completely unnecessary new object I’ve constructed simply to call code that really should’ve been able to handle my original object in the first place.
By writing methods that take interfaces as parameters, you make your code more flexible and more powerful, and you avoid imposing inappropriate restrictions (give me an X, even though I could just as easily do this with a Y) on calling code.