Let’s say we’ve got a generic list like this:
List<string> list = new List<string>() { "abc", "demo", "stackoverflow" };
When trying to create a new instance of a stack like this, it won’t work.
Stack<string> stack = new Stack<string>() { "abc", "demo", "stackoverflow" };
The compiler says that the Stack<> doesn’t have an add method. So I implemented an add method by using the extensionmethods:
public static void Add<T>(this Stack<T> stack, T item)
{
stack.Push(item);
}
However, the compiler still gives the same error. But why? Shouldn’t the compiler find the method now? Moreover, doesn’t the generic stack implement IEnumerable<> and ICollection<>? Why doesn’t the stack contain the Add method by default?
Collection initializers do not use extension methods; as such, you cannot use a collection initializer with something that does not have an
Addmethod-group, such asStack<T>. You could perhaps subclass it, but please don’t: