Search code examples
c#referencepass-by-referencevalue-typereference-type

Teaching References in C#


In a couple of weeks, I'll be teaching a class of first-year engineers the salient points of references in C# as part of their first-year programming course. Most of them have never programmed before, and had enough trouble learning objects, so teaching references is going to be an uphill battle. I plan to have lots of examples available for the students to go through on their own, but just showing a bunch of examples tends to be pretty overwhelming if the the underlying concept doesn't 'click'.

So I'll put the question out to the SO community: what's the best way you've seen references taught? What made it 'click' for you? Is there any reference-related material that I'm missing?

My tentative lesson plan is:

  1. What is a reference (using an argument like Eric Lippert's)
  2. References and the Garbage Collector
  3. Reference Types and Value Types
  4. Immutable Types
  5. Passing by Reference versus Passing by Value (and all of the subtleties of object references being passed by value)
  6. A handful of nasty examples that produce unexpected results if you don't understand 1-5.

Solution

  • One way that I've heard it explained is to use a cell phone or walkie-talkie. You (the instructor) hold one end and declare that you are an object instance. You stay in one place (ie. the heap) while the students pass the other end (which is on speaker phone if it's a cell phone) around the classroom.

    They can interact with you through the "reference" they have to you, but they don't really have "you" in their possession.