Datasheet
26
x
CHAPTER 1 PRIMER
On top of all this, the language can start to make the explicit “generic” declarations of the earlier
C# operations less necessary, because now the compiler will have the ability to infer the actual types
of the parameters, and with it, the ability to infer them as generic type parameters:
var swap = delegate (l, r) {
var temp = r; r = l; l = temp;
};
Here, the compiler can infer that l and r are of the same type, but that actual type is entirely irrele-
vant, because any type (class or struct, user-defi ned or BCL) can satisfy the inferred type parameters
for
l and r.
This would make much of the earlier code around currying so much, much easier to write and
understand.
IMMUTABILITY
As an old joke goes, a man walks into a doctor’s offi ce and says, “Doctor, it hurts every time I do
this” and jabs his thumb into his eye. The doctor, without missing a beat, says “Well, don’t do that,
and you’ll be fi ne.” Concurrency experts have long had a similar joke: If it hurts to write the locking
code around every time the program changes state, then don’t change state and you’ll be fi ne. After
all, if the variable never changes its state, then no update operation is possible and thus no locking
code around those updates are necessary.
Although the proponents of fully-immutable variable state (also known as the “pure functional
language”) continue to wage loud and copious arguments against those who favor the merits of
partially mutable variable state (the “impure language”), too many systems and libraries in the
.NET ecosystem rely on the capability to change variable state in a running program to abandon
the idea of mutable state entirely. That said, many objects in a .NET program remain immutable
when initialized, and many other types could do so with little concern or change to their use:
Person talbott = new Person(“Talbott”, “Crowell”, 29);
Person olderTalbott = new Person(talbott.FirstName,
talbott.LastName, talbott.Age + 1);
Enforcing this, however, requires the developer writing the class type to ensure there’s no way to
modify the contents of those instances. This means that fi elds must be marked as read-only and
properties with just a “get” handler.
If, however, the presumption is that most objects will remain unchanged when created, then rather
than assuming the objects should be mutable by default, the language can make the opposite
assumption and require the use of a keyword to indicate mutability.
Thanks to the power of inference, the programmer no longer has to stress over the low-level physical
details of how the code projects itself onto the underlying CLR. Plus, perhaps surprisingly, none of
the earlier syntax needs to change — the compiler simply chooses to generate the code differently, to
be immutable by default instead of mutable.
c01.indd 26c01.indd 26 10/1/2010 3:20:39 PM10/1/2010 3:20:39 PM