Generics, Params, IEnumerables (well, yield), Oh my!

Hello all,

Well, what once was a simple weekly email about cool stuff I ran across while working in DotNet has suddenly become very complicated. I spoke briefly with the devs on Generics the other day and wanted to throw together a more concrete example of using them. In the attached solution you will find a quite thorough example of using generics in a BinaryTree class I wrote. It’s important to remember that T is simply a type and tells your code what type to expect. Please ignore the bit of kludge in the AddNode method between IComparable and IComparable<T>. This was meant to be thrown together and I didn’t want to spend too much time on it.

In case you missed it above, here is the attached solution

In looking at the code for Form1 you can see the generics in action in the button1_Click event. The power of generics really comes through for compile time issues with not having to worry about casting. Here we create trees for int, string and a class I added called City. Since City implements IComparable we can use it for the tree.

By declaring,

BinaryTree<int> intTree = new BinaryTree<int>();

we know we have a btree that has ints and without casting we can do with
those ints as we please. Then any methods in the btree knows that the
value is an int.

This btree example, however, has two other things that are pretty cool.
The first is the use of an add method that takes
params T[] Items

I love using params as it allows for variable length parameters on
methods. Um, well, not a lot to say on params, just that they’re cool.

The other cool thing is the usage of yield in the ScanInOrder method.
yield basically allows you to return from a method when iterating over a
list of items where the code will remember where you were at so that you
can return back to that position. The cool thing about using yield is
that, as shown in the sample, you can use yield multiple times in the
same method. As we all know for an InOrder traversal of a binary tree
we basically move down the left side of the tree, give our value and
then start working on the right side of the tree (well, y’all know its a
bit more then that but I don’t think I have to explain it). Here in the
ScanInOrder method of the BinaryTree class it recursively calls
ScanInOrder on the left nodes of the tree items iterating in a foreach
loop yielding each of the results. Then it returns it’s own result and
finally recursively iterates in a foreach loop over the nodes on the
right side of the tree yielding each of those results.

In the morning my son Edison and I watch Curious George together on the
couch. Right before the cartoon starts KUAT does this cutesy animation
with a song in the back ground that says, “Learn something new
everyday. You learn a lot that way.” Hopefully I’ve helped with that
goal, 🙂

Brian

Leave a Reply