Datasheet
Chapter 1
12
Managed Code
The role of the CLR doesn't end once we have compiled our code to MSIL and a JIT compiler has
compiled this to native code. Code written using the .NET Framework is managed when it is executed
(this stage is usually referred to as being at "runtime"). This means that the CLR looks after our
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, that, for example, access low-
level functions of the operating system. However, in C# we can only write code that runs in a managed
environment. We 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 has mostly been 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. This usually meant a progressive slowdown of
your computer followed by a system crash.
.NET garbage collection works by inspecting the memory of your computer every so often, and removing
anything from it that is no longer needed. There is no set timeframe 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. Since 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 waiting for garbage collection to happen, but this isn't anything like as
tricky as it sounds.
Fitting it Together
Before moving on, let's summarize the steps required to create a .NET application as discussed above:
1. Application code is written using a .NET-compatible language such as C#:
C#code
2. This code is compiled into MSIL, which is stored in an assembly:
C#application
code
Assembly
Compilation