Extension methods, explicitly implemented interfaces and collection initializers
This post is the answer to yesterday’s brainteaser. As a reminder, I was asking what purpose this code might have: public static class Extensions { public static void Add<T>(this ICollection<T> source, T item) { source.Add(item); } } There are plenty of answers, varying from completely incorrect (sorry!) to pretty much spot on. As many people noticed, ICollection<T> already has an Add method taking an item of type T. So what difference could this make? Well, consider LinkedList<T>, which implements ICollection<T>, used as below: // Invalid LinkedList<int> list = new LinkedList<int>(); list.Add(10); That’s not valid code (normally)…. whereas this is: // … Continue reading Extension methods, explicitly implemented interfaces and collection initializers