0

A fellow OOP beginner here. I just had to do an exercise, where i had to create a custom class in C#, and on the homework TODO's there was a requirement to implement the IENumerable and IENumerator interfaces, and create a custom Queue of my custom class type objects.

While i had no issues solving the problem, i still don't understand the usage of this. Instead of writing so much code to implement a custom Queue, why not simply use the already existing "Queue" from the C# Framework? Is there any performance/optimisation advantage from this ?

So, is there any gain in using MyCustomObjectQueue, instead of using Queue<'MyCustomObject'> ?

Alex Ivan
  • 75
  • 1
  • 6
  • 2
    You're being taught concepts, this isn't something you'd do in a real world setting under normal circumstances. – Preston Guillot Sep 20 '20 at 18:22
  • What percentage of your high school (insert subject here) do you reckon you've actually applied in the real world, since leaving ? – Caius Jard Sep 20 '20 at 18:31
  • @CaiusJard 10% maybe ? But i get your point :D – Alex Ivan Sep 20 '20 at 19:05
  • As an aside, it's probably reasonable to expect that either a) your code performs better than the standard inplementation for the very narrow and direct problem that it solves or b) it performs worse because Microsoft hired a very clever beard to write theirs and it pulls some natty tricks that you don't know about. The only way to see which wins in the performance contest is to bench them by whatever metric you care about. This question probably belongs more on SE.SE than SO – Caius Jard Sep 20 '20 at 19:55
  • When you implemented IEnumerable (and likely IEnumerable), did you use `yield return` or did you actually implement the interface and create a class that implements IEnumerator (/)? You should try it the other way and then think about how `yield return` works under the covers – Flydog57 Sep 21 '20 at 00:08

1 Answers1

0

As mentioned in the comments, this is an excercise to familiarize you with the concepts. In the real world you would just about always use the existing queue implementation.

But the exercise is not pointless. Knowing how to implement IEnumerable is very valuable. IEnumerator is a bit less so, since you can use an iterator block to let the compiler do it for you.

The collections in the framework are made for generic usage, if you have some special usage patterns it can sometimes be useful to make your own variant, but this would be rather rare.

In my experience the most common cases for implementing a collection is to either wrap an existing collection to add some extra features, or implementing collections that are not provided, like a ringbuffer or heap.

JonasH
  • 28,608
  • 2
  • 10
  • 23