Datasheet
Part I: The C# Language
6
Managed Code
The role of the CLR doesn ’ t end once you have compiled your code to MSIL, and a JIT compiler has
compiled that to native code. Code written using the .NET Framework is managed when it is executed
(a stage usually referred to as runtime ). This means that the CLR looks after your applications by
managing memory, handling security, allowing cross - language debugging, and so on. By contrast,
applications that do not run under the control of the CLR are said to be unmanaged, and certain languages
such as C++ can be used to write such applications, which, for example, access low - level functions of the
operating system. However, in C# you can write only code that runs in a managed environment. You will
make use of the managed features of the CLR and allow .NET itself to handle any interaction with the
operating system.
Garbage Collection
One of the most important features of managed code is the concept of garbage collection . This is the .NET
method of making sure that the memory used by an application is freed up completely when the
application is no longer in use. Prior to .NET this was mostly the responsibility of programmers, and a
few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of
being allocated to the wrong place in memory. That usually meant a progressive slowdown of your
computer followed by a system crash.
.NET garbage collection works by inspecting the memory of your computer ever so often and
removing anything from it that is no longer needed. There is no set time frame for this; it might happen
thousands of times a second, once every few seconds, or whenever, but you can rest assured that it
will happen.
There are some implications for programmers here. Because this work is done for you at an
unpredictable time, applications have to be designed with this in mind. Code that requires a lot of
memory to run should tidy itself up, rather than wait for garbage collection to happen, but that isn ’ t as
tricky as it sounds.
Fitting It Together
Before moving on, let ’ s summarize the steps required to create a .NET application as discussed
previously:
1. Application code is written using a .NET - compatible language such as C# (see Figure 1 - 1 ).
C#code
Figure 1-1
CH001.indd 6CH001.indd 6 10/22/10 3:43:50 PM10/22/10 3:43:50 PM