John Munsch explains it like this:
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.
What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.
In designing an object-oriented application, a major tenet of design is “loose coupling”. Objects should only have as many dependencies as is needed to do their job – and the dependencies should be few.
There are three primary approaches to implementing DI:
- Constructor injection
- Setter injection (also called Property injection)
- Method injection
Constructor injection uses parameters to inject dependencies. In setter injection, you use setter methods to inject the object’s dependencies. Finally, in interface-based injection, you design an interface to inject dependencies.
The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the information that you want.
It is not be used to add or remove items from the source collection to avoid unpredictable side effects. (If you need to add or remove items from the source collection, use a for loop.)