Chapter 8. Enums and Collections; Storing lots of data

image with no caption

When it rains, it pours.

In the real world, you don’t get to handle your data in tiny little bits and pieces. No, your data’s going to come at you in loads, piles, and bunches. You’ll need some pretty powerful tools to organize all of it, and that’s where collections come in. They let you store, sort, and manage all the data that your programs need to pore through. That way, you can think about writing programs to work with your data, and let the collections worry about keeping track of it for you.

Strings don’t always work for storing categories of data

Suppose you have several worker bees, all represented by Worker classes. How would you write a constructor that took a job as a parameter? If you use a string for the job name, you might end up with code that looks like this:

image with no caption

You could probably add code to the Worker constructor to check each string and make sure it’s a valid bee job. However, if you add new jobs that bees can do, you’ve got to change this code and recompile the Worker class. That’s a pretty short-sighted solution. What if you have other classes that need to check for the types of worker bees they can be? Now you’ve got to duplicate code, and that’s a bad path to go down.

What we need is a way to say, “Hey, there are ...

Get Head First C#, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.