I have a class, Deck, that contains a method called Shuffle.
I’m working on refactoring Deck to extend List<Card>, rather than having List<Card> Cards as a property. However, while Cards.OrderBy (a => Guid.NewGuid ()) worked, OrderBy (a => Guid.NewGuid ()) does not:
Error CS0103: The name 'OrderBy' does not exist in the current context (CS0103)
Why does this not work?
Add
thisto the front ofOrderByas inOrderByis an extension method onIEnumerable<T>and is not a public method onList<T>. If you typeOrderBywith no context the compiler will look for an instance or static method namedOrderBy. It is only if you prefixOrderBywith an instance ofIEnumerable<T>will the compiler findOrderBy. AsDeck : List<Card>andList<Card> : IEnumerable<Card>, using the keywordthis(a reference to the current instance) will give the compiler the context it needs to locate the methodEnumerable.OrderBy.It is considered bad practice to inherit from
List<T>in a public API. First,List<T>was not designed for inheritance and probably should have beensealed; too late for that now. In general, you should favor composition over inheritance when using framework classes.