Introduction to the net framework l.jpg
Sponsored Links
This presentation is the property of its rightful owner.
1 / 118

Introduction to the .NET Framework PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

Introduction to the .NET Framework. Richard Grimes Richard Grimes. .NET contributer Dr Dobb’s Journal Visual C++ .NET columnist for Windows Developer Magazine C# Q&A column for C#Pro Contributor to MSDN Magazine

Download Presentation

Introduction to the .NET Framework

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Introduction to the .NET Framework


© 2004 Richard Grimes

Richard Grimes

  • .NET contributer Dr Dobb’s Journal

  • Visual C++ .NET columnist for Windows Developer Magazine

  • C# Q&A column for C#Pro


  • Contributor to MSDN Magazine

  • Twice monthly .NET email newsletter


© 2004 Richard Grimes

Richard Grimes

  • Developing Application with Visual Studio.NET, Addison Wesley, 2002

  • Programming with Managed Extensions for Microsoft Visual C++ .NET, Microsoft Press, 2003

© 2004 Richard Grimes

Aims For The Day

  • Gain an understanding of the .NET architecture

  • Understand the basic features and facilities of .NET

  • Gain an overview of the .NET framework library

© 2004 Richard Grimes

.NET Types and Objects

  • Everything in .NET is an object

    • reference types

    • value types (including enums)

    • ‘boxed’ value types

  • Reference types are created on the managed heap

  • Value types are created on the managed stack

© 2004 Richard Grimes

.NET Types


Reference Types

Value Types






© 2004 Richard Grimes

.NET Types and Objects

  • Reference types have System.Object as the highest base class

    • must be created on heap with new

  • Value types have System.ValueType as base class, Enums have System.Enum as bass class

    • must be created on stack or embedded as a member of a reference type

© 2004 Richard Grimes

Memory Layout

  • You should not care because data is accessed through members, not pointers

  • For interop with native code you can use a value type as a .NET representation of native structures

    • can specify the memory layout in this case

© 2004 Richard Grimes


  • Standard mechanism to handle ‘exceptional’ situations

  • Code can be ‘guarded’

    • clause to catch exception from guarded code

    • clause that is run when guarded block is left for any reason

  • Uncaught exceptions are passed up the call stack

© 2004 Richard Grimes

Exception Handlers

  • Can catch all exceptions or specific exceptions

  • Can provide exception handlers for many different exception types

    • handler handles exception and the exception types derived from it

© 2004 Richard Grimes

Type Members

  • Reference and Value types have

    • methods, fields, properties

  • Interfaces

    • have only methods and properties

  • All types can have events

    • metadata for delegate fields and a standard protocol to initialise them

© 2004 Richard Grimes


  • Can be overloaded on parameter

    • methods with the same name differ by the parameters that they

    • cannot have default values for parameters

  • By default parameters are ‘by value’

    • value passed on the stack, if you pass a reference type the reference is passed ‘by value’ not the object

    • can user modifier to pass by reference

© 2004 Richard Grimes


  • Data members

    • read and write access

  • Can define const fields

  • C# can define readonly fields

© 2004 Richard Grimes


  • Metadata that identifies methods to be used for read/write access

    • can implement either or both

  • Can add extra logic in property method

    • and can calculate values

  • Can implement Indexers

    • ‘indexed’ collection

© 2004 Richard Grimes


  • Constructor is called when an object is created

    • can overload constructors

  • ‘Destructor’ is called when object is finalized

    • you do not determine when this happens

© 2004 Richard Grimes

Virtual Members

  • When a member is marked as virtual the runtime uses the object type to determine what method to call

  • Used in polymorphism

    • allows you to pass a derived object through a base class parameter and the ‘right’ method will be called

© 2004 Richard Grimes

Static and Instance

  • Static members are not members of any particular instance

    • static fields are available to all instances

    • values of instance fields are specific to the instance

  • Static methods are executed in the context where they are called

    • instance methods are executed in the context where the object was created

© 2004 Richard Grimes


  • .NET only supports single type inheritance

    • only reference types, value types are ‘sealed’

  • .NET supports multiple interface implementation

    • and interfaces can have multiple ‘inheritance’

  • Can derive from classes written in any language

© 2004 Richard Grimes

Access Modifiers

  • Define whether the type is visible outside of the assembly

  • Define access to a member from

    • types within the same assembly

    • types in another assembly



public class

public class

internal class

internal class

Access Modifiers - Members

Access From

.NET Modifier

C# Modifier





Any class

Any class


protected internal

Only derived

Any class




Any class



Only derived

Only derived



Only derived




This class

© 2004 Richard Grimes

Managed Heap

  • Heap is managed by the garbage collector

    • cheap to allocate, expensive to compact

  • The GC will periodically remove old objects and compact the heap

    • objects that are not ‘reachable’ will be removed

© 2004 Richard Grimes


  • Objects are removed when the GC works, no sooner

  • ‘Finalizers’ perform clean up work

    • called when object is removed from heap

    • can be a long time after the object was last used

  • Use Dispose pattern instead

    • clean up code called explicitly by your code

© 2004 Richard Grimes


  • Are ‘reference’ types

    • but always refers to an object

  • Object can force caller to call interface through interface reference, or allow call through object reference

  • Interfaces do not contain

    • storage, constructors, static members, method implementations

© 2004 Richard Grimes


  • Common Language Specification defines rules that allow code written by one language to be used by code written by another language

    • not all code is CLS Compliant

© 2004 Richard Grimes


  • Types are contained in assemblies

    • libraries, DLLs, can be shared between processes

    • EXEs are processes

  • Typically libraries do not run ‘on their own’

    • but ASP.NET applications are libraries because .NET provides a host process

© 2004 Richard Grimes

Executing Code

  • All code is compiled to Intermediate Language

  • .NET runtime will just-in-time compile this to native machine code at runtime

    • on a per method basis, the compiled code is cached in memory

  • Can pre-JIT the code

© 2004 Richard Grimes

Assembly Loader




Architecture - Loading

Assembly Resolver

.NET Runtime

JIT Compiler

Compiled Code


.NET Framework Libraries

© 2004 Richard Grimes

Accessing Non .NET Code

.NET Process

Native Library

Platform Invoke

COM Interop

Native Library


Native Process

.NET Library

COM Interop

.NET Hosting

.NET Library

© 2004 Richard Grimes



.NET Remoting

.NET Remoting


Architecture - Execution


Application Domain

Application Domain


Application Domain

© 2004 Richard Grimes

Basic Objects

  • Primitive Types

  • Collections

  • Arrays

  • Strings

© 2004 Richard Grimes

Primitive Types

  • Part of the framework library

  • Used by all languages

    • the CLS primitive types, that is

  • Encapsulates operations on those types

    • conversions to other types

    • comparisons with other instances

© 2004 Richard Grimes

Primitive Types

CLS Types

Non-Compliant Types

Framework Type

C# Type

Framework Type

C# Type





























© 2004 Richard Grimes


  • Defines standard collection classes and interfaces

    • ICollection, has count and synchronised access

    • IComparer, compare items in a sorted collection

    • IDictionary, access to a key-value collection

    • IList, items are accessed by index

    • IEnumerable, exposes an enumerator that iterates over the collection

© 2004 Richard Grimes


  • Single and multiple dimensions

  • Typed, index is zero-based

  • Size specified at declaration

  • Access given by index and via an enumerator

    • implements IEnumerable, IList, ICollection

  • All access is bounds checked

© 2004 Richard Grimes


  • Contains an array of Char (Unicode)

  • Encapsulates all string operations

    • copy, replace, insert, remove, trim, sub string, uppercase, lowercase, compare, format, split, index of, last index of, pad left and right

  • Immutable

  • Interned

    • two string objects may be the same string, the string is interned

© 2004 Richard Grimes


  • Metadata describes types

    • all types have metadata

    • can extend metadata with ‘custom’ metadata

  • Runtime can read custom metadata as ‘out of band’ information

© 2004 Richard Grimes


  • The combination of metadata and IL means that anyone can ‘read’ your algorithm

    • can alleviate this with obfuscation

    • only solution is DRM with Longhorn

© 2004 Richard Grimes


  • Changes the metadata on a type

    • some add runtime metadata (eg [Serializable]

    • some add new metadata that is known by the runtime (eg [STAThread])

    • some add metadata that is not known by the runtime, but known by other classes and code (eg [Conditional])

© 2004 Richard Grimes

Metadata APIs

  • The Reflection namespace allows you to read metadata at runtime

    • allows you to dynamically invoke methods and properties, and access fields

    • and can read attributes

  • The Reflection Emit API allows you to write metadata at runtime

    • create metadata and IL

© 2004 Richard Grimes


  • Unit of deployment and security

    • defines the boundary of security and of type definition

  • Can contain multiple modules

    • each module is written in a single language

    • assembly can consist of modules written in many different languages

    • can also have other resource files

© 2004 Richard Grimes

.NET Containers



External Resources



Internal Resources


Configuration File


© 2004 Richard Grimes

Assembly Names

  • Assembly name contains four parts

    • PE file name

    • version

    • culture

    • public key/public key token

  • EXEs don’t use culture other than neutral

© 2004 Richard Grimes

Assembly Names

  • Assembly name uniquely identifies a library

  • Usually processes are ‘statically’ linked to libraries

    • library name is stored in the manifest of the files that use it

    • process will not load if the specific assembly cannot be found

© 2004 Richard Grimes

EXEs and Libraries



libOne, version=, culture=neutral, publicKeyToken=null

libTwo, version=, culture=neutral, publicKeyToken=null


version=, culture=neutral, publicKeyToken=null


version=, culture=neutral, publicKeyToken=null

© 2004 Richard Grimes

Assembly Location

  • In most cases the libraries will be in the same folder as the process

    • can be in a folder with the name of the PE file

    • if the file has culture specific resources, then it’ll be in a folder with the culture name

  • Can be shared by putting it in the Global Assembly Cache

© 2004 Richard Grimes


  • Appears to contain multiple files with the same name but different version

    • actually implemented with multiple folders

  • Contains assemblies

    • shared by other assemblies

    • ‘publisher policy files’, used to alter the versioning policy

© 2004 Richard Grimes

Satellite Assemblies

  • Resource-only

  • Culture specific

  • Runtime ResourceManager class will load the assembly for the current thread culture

    • or fallback, ultimately to ‘neutral’ resources

© 2004 Richard Grimes


  • The most important part of .NET!

  • All arrays and string access is bounds checked

  • Stack is managed by .NET, so cannot overwrite return address

  • Code access security checks whether the code has the permissions to run

© 2004 Richard Grimes

Signing Assemblies

  • Use the publisher public/private key

    • hash is created from assembly, encrypted with private key and appended to the assembly

    • public key is added to assembly

  • Assembly user can decrypt the signed hash, create its own hash from the assembly and compare the two

© 2004 Richard Grimes

Assembly Validation

  • Check that the PE file is valid

    • ‘everything is where it should be’, eg entry point, resources, dependencies

  • Check that the metadata is valid

    • that the tables are valid

  • Check that the IL is valid

    • check that it is ‘correct’ IL

    • check that jumps are within a method

© 2004 Richard Grimes

Assembly Verification

  • Performed by the JITter

  • Checks IL that is valid to see if it is doing something unsafe

    • eg casting to an unrelated type, pointer access to data (which can be abused)

  • No definite algorithm, so .NET uses a conservative algorithm that may fail safe code.

© 2004 Richard Grimes

Code Access Security

  • CAS is in addition to Win32 security

  • Assemblies have ‘evidence’

    • usually the location from where the assembly was downloaded

  • .NET defines policies

    • map evidence to permissions

  • Permissions define what the code can do

© 2004 Richard Grimes


  • There are four defined policies

    • User, Machine, Enterprise, AppDomain

    • all but AppDomain are loaded from XML

    • AppDomain is programmatic

  • Total permissions are the intersection of the permissions given by each of the four policies

    • because policies only grant permissions

© 2004 Richard Grimes

Code Groups

  • A policy uses a code group to determine what permission set results from a particular evidence

  • Code group has

    • membership condition

    • permission set

© 2004 Richard Grimes


  • Define some action that the code is allowed to perform

    • trusted assemblies check that calling code has the permissions before performing the secured work

  • Permission Sets are combinations of permissions

© 2004 Richard Grimes


  • Trusted code calls Demand on a permission set

  • Demand causes a stack walk to check the permissions of every method

    • the evidence of the method’s assembly is put through the policy

    • the top of stack permissions comes from the intersection of the spawning thread’s call stack methods, or from AppDomain

© 2004 Richard Grimes

Demand and LinkDemand

  • Demand, the check is performed at runtime every time the method is called

    • whole stack is walked

  • LinkDemand is performed only at JIT time

    • security check is only performed on the method being JITted

© 2004 Richard Grimes

Imperative and Declarative

  • Imperative, code explicitly calls Demand

    • allows fine grain checks within the method

    • allows you to take remedial action in the method

    • can use information known only at run time

  • Declarative, methods are marked with permission attributes

    • applies to whole method

    • clear by looking at method what permissions are required

© 2004 Richard Grimes

Other Enforcement

  • Can explicitly Deny code with specific permissions

  • Can specify that only a specific permission set is allowed, PermitOnly

  • Sometimes a full stack walk is unfeasible

    • other code may not have the permission

    • Assert indicates that a permission is granted for all methods higher in the stack (but calling code must have the Assertion permission)

© 2004 Richard Grimes

Assembly Permissions

  • Assemblies can be marked with a permission set

    • if the calling code does not have the permissions the assembly is not loaded

© 2004 Richard Grimes

Role Based Security

  • Can rely on Win32 security

    • the process access token is used to see if access is given to a secured object

    • eg you cannot access access a file unless you have been given access

  • Can use .NET to get user identity and do runtime role based checks

© 2004 Richard Grimes


  • Configuration should be treated as read-only and non-dynamic

    • essentially like command line switches

  • Configuration is cached in each AppDomain

    • so if the config files change between creation of AppDomains the change will be read

© 2004 Richard Grimes

Configuration Files

  • Specific to application assemblies

    • <appname>.config, eg myApp.exe.cofnig

  • Application configuration file stored in same folder as application

    • default settings are in the machine.config

  • XML files with a schema defined by configuration sections

© 2004 Richard Grimes

Configuration Sections

  • Many system classes read configuration when they are initialized

  • Your code can read custom configuration

    • through <appSettings> section

    • or by defining your own configuration section

© 2004 Richard Grimes


  • Essentially read-only

    • Whidbey offers classes to write configuration, but these are not a solution

  • No per-user settings

  • Not applied to libraries (always reads config for app)

  • Not dynamic, because settings are cached

    • if config changes during run, objects do not reflect this

© 2004 Richard Grimes


  • All execution is performed on a thread

  • All processes have at least one thread and have a thread pool

    • each thread has a culture and can have a context

  • Threads can be background or foreground

    • app can close even while a beckground thread still runs

© 2004 Richard Grimes


  • A thread can be suspended and resumed

  • You can kill a thread

  • A thread can tell itself to sleep

  • You can change the priority of a thread

© 2004 Richard Grimes

Thread Procedure

  • Thread object is initialised with a ThreadStart delegate

  • Thread pool thread runs a WaitCallback delegate

  • In both cases you have to take other steps to return a return value

[Serializable] public delegate void ThreadStart();

[Serializable] public delegate void WaitCallback(object state);

© 2004 Richard Grimes


  • Framework provides classes to protect shared data and code

    • Mutex, Monitor

  • Provides classes for thread communication

    • AutoResetEvent, ManualResetEvent

© 2004 Richard Grimes


  • Enterprise Services (COM+) can be used to ensure that a single thread is used to access a collection of objects

  • Can also use MethodImplOptions.Synchronized to indicate that only one thread can access a method at a time

  • Also allows thread local storage and thread static data

© 2004 Richard Grimes

Threads and Exceptions

  • If an exception is not caught by a thread, the thread will die

  • If the thread is the only thread in the AppDomain, the AppDomain will die

    • often this will kill the process

  • ThreadAbortException can be caught, but thread will always die

    • unless the thread calls ResetAbort

© 2004 Richard Grimes


  • Contexts provide the environment in which your objects run

    • every object will run in a context, but not all objects care about the context

  • Contexts belong to an Application Domain

    • every Application Domain will have at least one context, called the default context

  • Threads are not connected to a specific context

    • a thread may execute code running in one or more contexts

© 2004 Richard Grimes

Component Services

  • Contexts are used to supply component services

  • When an object in a context creates another object it will be created in the same context

    • if its component services requirements do not clash with the context

    • if the object doesn’t care about component services

© 2004 Richard Grimes

Component Services

  • .NET Component Services are applied through interception

    • the object does not have to know that interception occurs

  • Most component services are the Enterprise Services

    • for objects that derive from ServiceComponent

© 2004 Richard Grimes

Objects and Contexts

  • Some objects are bound to a context

    • can only be executed in the context where they were created

    • derive from ContextBoundObject

  • Others are context agile

    • can move between contexts

    • don’t care what context they are used in

    • not derived from ContextBoundObject, or are marshal by value

© 2004 Richard Grimes

.NET Remoting

  • Gives access to context bound objects

  • Architecture has many extensibility points

  • Can add your own interception

    • to monitor calls to an object

    • to add your own component service

© 2004 Richard Grimes


  • Type safe .NET ‘function’ pointers

  • .NET methods are __clrcall, so C type function pointers do not work

  • Multicast

  • .NET automatically adds ‘thunks’ for delegates passed to native code

© 2004 Richard Grimes


  • A delegate class is generated by the compiler

    • derived from MulticastDelegate

  • Delegate object contains a linked list of delegates

    • when the top delegate is invoked, so are all delegates in the list

© 2004 Richard Grimes


  • The methods in the delegate must be in the same process

    • but .NET remoting can marshal a delegate to another process and invoke the method if a suitable channel is created

  • Delegates can be serialised

© 2004 Richard Grimes

Asynchronous Calls

  • Every delegate can be invoked asynchronously

    • without any extra code

    • performed on a thread pool thread

  • Some Framework APIs provide asynchronous methods that use Win32 asynchronous functions

© 2004 Richard Grimes


  • Events are metadata that formalizes the protocol of adding delegates to an object that are used for notifications

  • Compiler generates methods for the event and adds storage for the delegate

    • methods to raise the event and add and remove a delegate

    • can provide your own

© 2004 Richard Grimes

Object Serialization

  • Object serialization is important for

    • persistent storage of objects

    • passing objects across contexts

    • using the message queuing classes

  • Framework provides classes to serialize to XML and to binary

© 2004 Richard Grimes


  • [Serializable] is used to mark a class that can be serialised

    • fields are serialised

  • [NonSerialized] is used on fields that should not be serialised

  • Can use custom serialisation to handle fields that cannot be serialised

© 2004 Richard Grimes


  • Framework provides classes to serialize to

    • binary: BinaryFormatter

    • SOAP XML: SoapFormatter

    • raw XML: XmlSerializer

  • In general these will serialize an object to a stream and deserialize from a stream

© 2004 Richard Grimes

Raw XML Serializer

  • XmlSerializer is used to create XML from the state of an object

    • does not need [Serializable]

    • the object can have attributes to indicate how the state maps to XML, indicating node names and attributes

  • It cannot handle circular references

    • member objects are embedded as child nodes

© 2004 Richard Grimes

Raw XML Serializer


<?xml version="1.0"?><MyObject xmlns:xsd="…"> <o> <x>99</x> <s>test</s> </o></MyObject>

int x;string s;


MySubObject o = {99, "test"};

© 2004 Richard Grimes

Raw XML Serializer


[XmlAttribute("Age")] int x;[XmlAttribute("Name")]string s;

<?xml version="1.0"?><MyObject xmlns:xsd="…"> <Person Age="39" Name="Richard" /></MyObject>


[XmlElement("Person")]MySubObject o = {39, "Richard"};

© 2004 Richard Grimes


  • Do more work serializing objects

    • take into account references to objects

  • Formatters

    • implement IFormatter

    • use the ObjectManager to determine the order that child objects are deserialised

© 2004 Richard Grimes


public interface IFormatter{ SerializationBinder Binder {get; set;} StreamingContext Context {get; set;} ISurrogateSelector SurrogateSelector {get; set;} object Deserialize(Stream); void Serialize(Stream, object); }

© 2004 Richard Grimes

IFormatter Properties

  • Context used to determine where the object is being serialized

  • Binder is an object used to determine the type of the class when the object is deserialised

  • SurrogateSelector is a separate object to do serialization

    • used in the remoting case for MarshalByRefObjects

© 2004 Richard Grimes


  • Consulted by formatter while deserialising an object

    • keeps a list of child objects

  • Ensures that child object is deserialised only once

    • ObjectManager returns child object if it has already been deserialised, otherwise child object is added to ObjectManager

© 2004 Richard Grimes

Custom Serialization

  • [Serializable] cannot be used with objects that hold handles or pointers

    • because the items they refer to will not be serialized, only the opaque handle

  • Can use custom serialization to control what is serialized

© 2004 Richard Grimes


  • This has just one method: GetObjectData(), used to get the state of the object

  • The interface is unusual because if your class implements this interface then it must implement a constructor that takes the same parameters

void GetObjectData(SerializationInfo info, StreamingContext ctx);

© 2004 Richard Grimes


  • This is a name-value collection

  • It has Add* methods to add primitive types and objects

    • interestingly, the objects that you add do not have to be [Serializable]

  • It has Get* methods to retrieve values

  • Also has GetEnumerator()

© 2004 Richard Grimes


  • Many of the framework uses streams

    • files

    • sockets

    • crypto-routines

  • System.IO.Stream base class provides the common functionality

    • both synchronously and asynchronously

© 2004 Richard Grimes

Stream Classes

© 2004 Richard Grimes


  • Support for

    • reading and writing a single byte

    • reading and writing an array of bytes

    • determining if seeking a position within the stream is supported

    • flushing the stream if it is buffered

© 2004 Richard Grimes

Readers and Writers

  • Stream access is by bytes only

    • must make an intelligent interpretation of those bytes

  • Readers and Writers are used to perform that interpretation

    • Constructor takes stream reference and encoding for strings

© 2004 Richard Grimes

Reader and Writers

© 2004 Richard Grimes

Readers and Writers

  • TextReader, TextWriter, abstract classes, convert between primitive types and strings

    • write data as strings, read strings and convert to appropriate type

  • StreamReader, StreamWriter, are TextReader/Writer that read and write strings

  • BinaryReader, BinaryWriter read/write the underlying bytes of the data types

© 2004 Richard Grimes

Text Encoding

  • Supports

    • UTF7, UTF8, Unicode (bigendian, littleendian), ASCII

  • Readers can be constructed with an encoding, or can guess the encoding

  • Writers will write a ‘preamble’ that identifies the encoding

    • use UTF7 or ASCII if you don’t want the preamble

© 2004 Richard Grimes

File Access

  • File and FileInfo return an FileStream

    • can also use FileStream constructor

  • Can specify the file access and sharing options similar to Win32

  • Can determine whether file is created or appended

© 2004 Richard Grimes

File Access

  • FileAccess, determine how you access the file

    • Read, ReadWrite, Write

  • FileShare, determines whether the file can be accessed by anyone else

    • Read, ReadWrite, Write

© 2004 Richard Grimes


© 2004 Richard Grimes

Accessing Part of a File

  • Can use FileShare to determine if other users can access the file while you are using it

  • If you allow ReadWrite access to a file then you should lock the regions that you write to

    • FileStream.Lock(), FileStream.Unlock()

© 2004 Richard Grimes


  • Diagnostics are used to add instrumentation to make it easier to debug

    • conditional code

    • tracing

    • asserts

    • stack traces

© 2004 Richard Grimes


  • The [Conditional] attribute can be applied to a method

    • indicates that the method is called only if a specific symbol is defined

  • Most compilers will simply ignore the method if the symbol is not defined

    • however C++ is an exception

© 2004 Richard Grimes

Conditional Code

  • Use the language syntax to specify that a block of code will only be compiled if a symbol is defined

  • Symbols are usually defined on the command line or in the source code

    • can make the source code difficult to read

© 2004 Richard Grimes

Trace and Debug

  • Both contain code for tracing and asserts

  • Trace methods are called only if TRACE is defined

  • Debug methods are called only if DEBUG is defined

  • C# wizards define TRACE for Debug and Release builds (ugh!)

© 2004 Richard Grimes

Tracing Code

  • Allows you to provide debugging messages at runtime

    • WriteLine and Write

    • messages are sent to each listener in the trace listener collection

  • Can specify a Boolean to control whether message is written

    • WriteLineIf and WriteIf

© 2004 Richard Grimes

Trace Listeners

  • All trace messages are sent through the process’s trace listeners collection

    • usually specified through the config file

    • can be specified programmatically

  • Trace listeners derive from the TraceListener class

© 2004 Richard Grimes

Trace Listeners

*Note that this works only for single threaded code. There is no thread synchonization. It fails for multiple AppDomain code.

© 2004 Richard Grimes


  • Asserts indicate that the process is in an unstable state and should not continue

    • in a debug session you can still decide to continue to execution

  • Optionally, you can direct asserts through a listener to a file

© 2004 Richard Grimes

Debug Symbols

  • When the code is compiled for debug

    • extra information is stored in symbol files with variable names, source line numbers etc

    • turns off JIT optimization

    • turns on runtime tracking of objects

  • Makes stack traces useful

© 2004 Richard Grimes

Stack Traces

  • The StackTrace class can be used to dump information about the call stack

  • For a command line app this is displayed when an exception is not caught

  • For a GUI application this information is displayed in a dialog

© 2004 Richard Grimes


  • Use [DebuggerHidden] to indicate that the debugger should not step into the method, nor allow breakpoints

  • Use Debugger.Break in your code to force a breakpoint in the debugger

    • users get the option of starting the debugger

  • Use Debugger.Launch to force the debugger to start

© 2004 Richard Grimes

The Framework Library

© 2004 Richard Grimes


  • Applied Microsoft .NET Framework Programming, Richter, Microsoft Press, 2002

  • Essential .NET, Volume 1, Box and Sells, Addison Wesley, 2002

© 2004 Richard Grimes

  • Login