Building high-performance systems often requires specialized data structures beyond the standard List. Furthermore, senior developers use Iterators to stream data to save massive amounts of RAM.
Every collection in .NET that works with foreach must implement the IEnumerable interface. By implementing this, your custom classes can participate in the entire LINQ ecosystem.
The yield keyword is a "State Machine" generator. It allows a method to return values one at a time, "pausing" and "resuming" execution automatically.
public IEnumerable<int> GenerateNumbers()
{
yield return 1;
// Execution pauses here and returns to the caller.
// When the caller asks for the next item, execution resumes here!
yield return 2;
yield return 3;
}
Standard List and Dictionary are NOT thread-safe. If you access them from multiple threads, your app will crash or suffer data corruption. Always use ConcurrentDictionary or ConcurrentQueue in multithreaded environments.
Q: "What is the difference between ICollection, IList, and IReadOnlyList?"
Architect Answer: "It's about the 'Principle of Least Privilege.' `ICollection` allows adding/removing but no index-based access. `IList` allows everything including index access (`list[0]`). `IReadOnlyList` is the safest; it allows index access but forbids any modifications (`Add`, `Remove`, `Clear`). In professional API design, you should return the 'most restrictive' interface possible. If your method shouldn't be allowed to change the list, return `IReadOnlyList