Credit Default Swap Index Trading: Bid/Offer, Rolls, Roll Conventions


I apologize in advance for the rather esoteric subject here, but I have in the past done some work with our CDS index trading desk.  The roll dates for the US indexes are once again approaching.  Immediately after the roll date we trade both the old index, the new index, and the roll between them.  The terminology, and what we are buying and selling, confuses us poor developers no end.  It is immensely confusing because of the price/spread conventions.

At the last roll I wrote some notes on this, which I’m publishing here to help anyone else struggling with the market.

This article focuses on the US CDS index trading market, and uses the Markit CDX indexes as examples.  This isn’t a general introduction to those markets, rather it’s a discussion of the mechanics of the market and what the bid/offer spreads actually mean.

I have written a general introduction to the credit default swap market.  Markit themselves have guides to the index markets (see the Primers section).

CDS Index Pricing

Some indexes trade on spread (e.g. CDX IG), some on price (e.g. CDX HY).  The series of articles on credit default swaps include a description of what these terms mean.

Indexes That Trade On Spread

In many ways spread is easier to think about.  In March 2012 some real prices quoted by a dealer were 90.0/90.5 for the CDX NA IG 18 index, 84.25/85.0 for the CDX NA IG 17, and 5.50/5.69 for roll.  I explain what these numbers actually mean below.

The Index Bid/Offer When Trading on Spread

The 18 price of 90.0/90.5 means that as a customer we pay the equivalent of a running premium of 90.5 to buy protection against defaults in the index, we receive 90.0 to sell protection.  Of course we don’t actually pay that premium, we pay a fixed premium of 100 and an upfront fee that adjusts for the difference to the quoted spread of 90.5.

As a customer we always buy at the offer, and sell at the bid.  Here we are buying protection at the offer (90.5).  So for a customer to ‘buy’ here means to buy protection.

The Roll When Trading On Spread

A roll trade is designed to swap a position in the old index into a position in the new index.  So you will sell protection in the old index and buy it in the new index, or vice versa.

The roll was trading at 5.50/5.69.  When you ‘buy the roll’ you, as usual, buy at the offer (at 5.69).  By convention for securities trading on spread you are buying protection on the new series (the 18), selling it on the old series (the 17).  I’m swapping a ‘long’ (bought protection) position in the 17 for a long position in the 18.

However, for reasons we shall see later it’s easier to think about bid and offer here.  If I buy the roll I’m trading at the offer price (5.69): I’m lifting the offer.  When I do that I’m also trading at the offer price for the 18, but trading at the bid price (hitting the bid) for the 17.

To calculate what trades you enter into at what prices if you trade the roll, you start with the 18 and work out the 17 from the roll spread.  You subtract the roll spread from the 18 price.  Note that this applies to indexes that trade on spread only: see below.

In this case if I buy the roll, I’m buying the 18 at the 18 offer (90.5) and calculate the 17 bid as 90.5-5.69 = 84.81.  Note that this is a better price for me than the actual outright 17 bid (84.25): I effectively receive premium at 84.81 instead of 84.25.

Note also that I haven’t crossed the spread on the 17: I’m trading at an implied 17 bid of 84.81 but this is still less than the offer of 85.00.  For obvious reasons this is an important check for a trader.

If I sell the roll at 5.50, I’m selling the 18 (at 90.0) and the implied 17 offer is 90.0-5.5 = 84.5, again a better price to me than the outright price of 85.0.

Indexes That Trade On Price

The CDX HY index trades on price.  In March 2012 some real prices quoted by a dealer were 97.56/97.75 for the CDX NA HY 18 index, 98.75/98.94  for the CDX NA HY 17 index and 1.19/1.31 for the roll.

The Index Bid/Offer When Trading On Price

Here buy protection/sell protection is reversed from above because of the way the index is quoted.  The 18 price of 97.56/97.75 means that as a customer I still ‘buy’ at the offer (97.75).  However, now this number is used to calculate my upfront fee directly, rather than referring to a notional spread over the life of the trade.  As discussed in my earlier article, the calculation is 100-price = points, and points is the percentage we apply to the notional to calculate the fee.

For the dealer to make money the customer has to pay more to buy protection than they would receive to sell protection.  Here if I ‘buy’ at 97.75 the associated fee is 2.25% of the notional, if I ‘sell’ at 97.56 the associated fee is 2.44% of notional.

What this means is that I’m actually buying protection at the bid (97.56) and selling protection at the offer (97.75), which is the reverse of trading on spread.

So for the HY index we are quoting ‘like a bond’.  If I buy the 18s at the offer (97.75) this is like entering a long bond position (buying a bond), going short protection.

To recap, the percentage fee I actually pay is 100 minus the quoted spread, so for the 18s this is 2.44/2.25.  So I receive 2.25 if I sell protection, pay 2.44 if I buy protection (percent of the notional).

The Roll When Trading On Price

The roll was trading at 1.19/1.31.

If I lift the offer on the roll (1.31) then I’m lifting the offer on the 17 and hitting the bid on the 18 (97.56).  Note that’s the reverse of what I did above for the IG.  This is just the convention: I explain why it’s the convention below.

However this is the SAME trade as lifting the offer on the roll for the IG in terms of buying/selling protection: I’ve sold protection on the 17, bought protection on the 18.

As for the IG we derive the 17 price for the roll from the 18 price and the roll spread.  Here we add.  Again I explain why this is the convention below.

So if I lift the offer on the roll I’ll calculate the implied 17 offer price by adding the roll offer price to the 18 bid price.

That is, the implied 17 = 97.56 + 1.31 = 98.87.  So we’ve sold protection on the 17 at 98.87, which means we receive more upfront fee than if we’d just lifted the offer on the outright 17 (98.94): remember we actually receive 100 minus the value here.  So the customer again gets a better deal by trading the roll than by trading the two outrights.

Note also we haven’t crossed the spread for the 17 (98.75 < 98.87 < 98.94).

Summary of Calculations When You Trade a Roll

Trading on Spread

New index 90.0/90.5

Roll 5.50/5.69


Customer buys roll (lifts offer), old index bid price = 90.5-5.69 = 84.81 (old bid = new offer – roll offer)

Customer sells roll (hits bid), old index offer price  = 90.0-5.50 = 84.5 (old offer = new bid – roll bid)

Trading on Price

New index 97.56/97.75

Roll 1.19/1.31


Customer buys roll (lifts offer), old index offer price = 97.56+1.31 = 98.87 (old offer = new bid + roll offer)

Customer sells roll (hits bid), old index bid price = 97.75+1.19 = 98.95 (old bid = new offer + roll bid)

Explanations for the Roll Conventions

The first thing to note is that in general it costs more to buy protection and you receive more if you sell protection in the newer index.  This is because the protection is for six months longer.  You may also have already had defaults in the old index so fewer names are being covered.  However, the index constituents are revised to include more liquid and better-quality credits and this can offset this effect to some extent.

Roll Spread Convention

This means that if you are trading on spread (new index spread- old index spread) is positive, because the new spread is larger, regardless of buy protection/sell protection.   We want to quote a positive spread, so we make that the calculation for our roll spread.

If you are trading on price then things are reversed:  (old index price – new index price) will be positive, so we make that our roll spread.  This is because the upfront fee is larger for the new index (it costs more to buy protection), so the actual price we quote is smaller for the new.

Hence the difference in the roll calculations: if trading on spread to get the old index spread we subtract the roll spread from the new index spread, if trading on price to get the old index price we add the roll spread to the new index price.

Bid/Offer Convention

The bid/offer conventions now follow from the above.  For both price conventions we will always have one trade at the bid and one at the offer in a roll.  We are always buying one index and selling the other.  There are alternative ways of quoting to those described above.  However, if we quote with the conventions described above we always have offer greater than bid, and are always buying protection on the newer index if we buy the roll, so it makes sense to do it this way.


I warned you it was confusing: hopefully this article at least gives some idea of what’s going on.

15-Minute Beginner’s Guide to Windows 8


Windows 8 has been released to manufacturing, and is available to developers on MSDN.  It’s quite disorientating for people who’ve worked with Windows for a while.  I’ve been playing with it and wrote some notes for myself, so I thought I’d turn them into a quick guide to navigating your way around it.

I’m going to assume you’re experienced with previous versions of Windows, you’ve managed to get Windows 8 installed, and have got past the logon screen to the start screen.  I’m also going to assume you’re a developer and therefore don’t like to reach for the mouse too much whilst working: there will be a lot of shortcut keys in this.  I’m also assuming you don’t have a touch screen.


The first thing to realize is that Windows 8 is intended to be both a desktop operating system (OS) and a tablet operating system.  This is logical: Microsoft need a version of Windows that can run on low-powered tablets, so they either had to write a new OS or make Windows itself capable of doing it.  They went for the latter.

However, desktop and tablet operating systems are inevitably slightly different.  Windows 8  on a PC is effectively a desktop operating system with a tablet operating system embedded in it.

Windows 8 Style User Interface (previously ‘Metro’)

The tablet part of the new OS has a new tiled user interface design, currently called the ‘Windows 8 style user interface’.  It also has tablet-style apps that run full screen.  There’s a store for the apps: it looks like Microsoft is going to pursue the proprietary locked-in approach to tablet software that other companies are using.  Apple fanboys might want to think about the effects of Apple’s approach on the industry.

Of course Windows 8 still has a full old Windows 7 style desktop within it, including all of the old desktop applications that don’t have to run full screen.

Start Screen

The start screen is the one you see in all the screenshots.

Think of the start screen as a fullscreen and more sophisticated version of the start menu in Windows 7.  It even starts in a similar way: you go to far bottom left of the screen and click.

Obviously you can click on any of the tiles to launch the new apps.  You can also click on tiles for old desktop apps, although you may need to set them up.  You can also navigate and launch apps by using the arrow keys and Enter.

You can get back to the start screen once you’ve launched an app if  you hit the Windows key, or, as already mentioned, if you move your mouse to the far bottom left and click.  Hitting the Windows key again will take you back to where you were.

Rearranging the Start Screen

You can drag tiles around on the start screen to rearrange them.  You can move the mouse to the far left or far right to scroll.  If you right-click the background to the start screen an option for ‘All Apps’ appears, and you can right-click one of these to add it to the main start screen.

You can zoom out by clicking the little minus sign in the bottom right of the screen.  This is useful if you’ve set up a lot of tiles.  It allows you to move groups of tiles around by dragging, and to name them, by right-clicking.


You can just start typing the name of your application with the start screen visible.  It will immediately show a search screen and filter down to your application in a few keystrokes, after which you can just hit ‘enter’.  Again this is very similar to starting an application with the keyboard in Windows 7 via the Start menu, except it’s faster and far more powerful.

You can also bring up the search screen from the charms menu (see below), or with Windows+q.

You can search for files or settings; just use the options underneath the search box. You can also search WITHIN an app in the same way.  For example, the way to search in the Wikipedia app is to use the Windows 8 search menu: there’s no visible search functionality in the apps own screens.

You can add applications to the start screen from the search screen as well.  Find the item you want to add with the search features and right-click it.

Windows 7 Style Desktop

You can get to the old style desktop by clicking on the desktop tile on the start screen, or by hitting Windows+d.  If the desktop is already running there are other ways of getting to it: more on this later.

The only really noticeable change in the new desktop is that the Start button has disappeared, to be replaced by the start screen as discussed above.  There are a few minor improvements to the desktop as well: for example, Task Manager is far more powerful, and if you do a large file copy you get a little chart of the speed over time in the copy dialog.  Also Windows Explorer now has a ribbon interface.

Missing from the Windows 8 desktop are the gadgets that you could set up on the desktop, and the Aero glass look for the title bars of the windows.  They aren’t available.  Window title bars don’t even have a gradient, they are just solid blocks of colour.  This is the new ‘chromeless’ look: it also affects things like scrollbars and buttons.

‘Charms’ Menu

Windows+c, or move mouse to bottom right or top left brings up the so-called ‘charms’ menu from anywhere.  It slides out from the right side of the screen.  This has icons for Search, Share, Start, Devices and Settings.  Search and Start bring up the relevant screens discussed above.


The Settings icon on the charms menu lets you access the full tablet settings screen by clicking on ‘Change PC Settings’ at the very bottom.  Here you can do things like change the picture on the lock screen or change the background to the Start screen (under ‘Personalize’), or change your password (under ‘Users’).

Tablet Apps

The tablet apps need work, although some of them are already pretty good.  Obviously you visit the Store app from the start screen to browse and install additional apps.  Here’s the default weather app, which has a lot more detail if you scroll to the right:

Many of the apps have menus in them.  To bring these up right-click on the background, or use Windows+z.

You can close an app with Alt + F4 or by moving the mouse to the top middle of the screen and dragging all the way to the bottom.  You can also right-click in the left-hand slideout menu mentioned above.

You usually have to scroll in an app by moving to the bottom of the screen and using the scrollbar that appears.  There don’t appear to be any mouse gestures to scroll.

Moving Between Apps

If you move the mouse to the bottom left and then move up, or to the top left and then move down, then a slideout menu appears on the left side of the screen with all the tablet apps previewed apart from the one you are currently in.  You can click on one to go to it.  This menu treats the entire desktop as one tablet app.

You can also bring up the slideout menu and tab between apps with Windows+Tab.  This is actually a bit annoying as it doesn’t include the current app so you can’t change your mind and stay where you are.

You can move to the last tablet app you were in by moving the mouse to the top left and clicking.

You can move between all open applications, desktop plus tablet, with Alt-Tab.

Tiling Tablet Apps

You can’t actually fully tile tablet apps, but you can show a main app and have a second one in a sidebar at the left- or right-hand side of the screen.  This is called the ‘Snap’ feature.  The sidebar will stay there as you show different apps in the main window area, including if you bring up the desktop.

By default this only works on fairly high resolution screens, 1366×768 or higher, which means it won’t work on most laptops or corporate desktops unfortunately.

To set this up bring up the lefthand slideout menu (bottom left and move up with the mouse), leftclick the open app that you want in a sidebar, and drag it into the sidebar position.

You can make the desktop itself into a sidebar, in which case it shows the open desktop applications.  You can also drag the sidebar divider to the right or left, which will close the sidebar or make it the main app.


There are actually two versions of Internet Explorer 10 in Windows 8: the tablet app version and the version that runs on the desktop.  The app version has a less easy interface, but more significantly it will only run Adobe Flash on certain websites that Microsoft has vetted as safe.  The desktop version has no such restrictions.

Old Windows Keys Combinations

Most of the useful old Windows keys combinations still work from anywhere, including in tablet apps.  So Windows+e will bring up a Windows Explorer window on the desktop from anywhere, Windows+m will go to the desktop and minimize all applications.

Start Screen Right Click Menu

If you move your mouse to the bottom left to bring up the start screen icon and then right-click instead of left-clicking you get a handy power user menu for desktop functionality.  This works from anywhere.  The menu includes options to go directly to the Explorer, Task Manager, Event Viewer, Control Panel, Search, Desktop or an admin Command Prompt.

Floating Point Arithmetic

We had a discussion about floating point arithmetic on 32-bit processors in our team this morning: here’s a brief note I made on the subject a long time ago.

double a = 95.0;
double b = 94.0001;
double c = a – b;

In .Net this give c = 0.99989999999999668. It should be 0.9999 obviously. This is a classic floating point problem: big numbers and small numbers don’t mix well for addition and subtraction. You get the same problem in Java. This is because there’s an IEEE standard for how 32-bit doubles (and other floating point types) should work, which is used in both languages.

The real problem is there’s no easy way of dealing with the fact that the real numbers are infinite and computers just aren’t. More to the point, for efficiency we really want to put some ceiling on our level of accuracy, and in particular we really only want to use 32 bits on a 32-bit processor.

There’s a lot of detail on this on the web, some of it extremely tedious with geeks showing off how mathematical they are, some of it containing sensible advice:

In both .Net and Java there are specific types that are designed to be slow but allow arbitrary accuracy: these are Decimal (.Net) and BigDecimal (Java). Actually Decimal isn’t designed for arbitrary accuracy, it’s 128 bits, but it solves the problem above.

In Excel of course you can’t use these. Excel cheats a little bit in that if you only display 4 DPs (which it does by some default magic) it rounds to that so it appears you get 0.9999. In fact if you set it to show 15DP you get the same answer as above.

Microsoft gives some sensible non-geeky advice about dealing with this in Excel: round. You can even round to what’s displayed because that’s designed to work and there’s a specific option to do it (although it warns that, of course, you’re losing quite a bit of accuracy if you do this everywhere in a complex sheet). In the .Net example at the top of the page you get the right answer if you do Math.Round(c, 14). Another technique used in Excel is to test for a floating point value to within a small epsilon (i.e. don’t test for 0, test for 0 plus or minus epsilon).

Creating Code Listings in WordPress using Visual Studio

In WordPress it has historically been quite hard to paste code listings into the editors and get them to look good.  There are some plugins that try to do it, but none of them seem to work very well with code copied out of Visual Studio.

Edit 2016:  Wordpress themselves have now solved the problem to some extent by allowing basic code blocks.  If you precede your code with ‘code language=”csharp”‘ in square brackets, and put ‘/code’ after it, also in square brackets, then you get something that looks as below:

static void MyMethod(int x, string y = "Hello", string z = "World")
Console.WriteLine(y + " " + z + ": " + x);

This still doesn’t work particularly well with a direct paste from Visual Studio: the code gets a little mangled with pre tags and some ‘Snippet’ text.  Easiest is to first paste into notepad and then recopy from there to ensure you are just pasting plain text.  Also it obviously isn’t quite as nice as the original code in Visual Studio.

The original article below explains how you can use the Productivity Power Tools to copy an HTML version into your article, although this is a little more involved.  This works in Visual Studio 2013 and 2015 as well as the versions listed below.


In Visual Studio from 2010 onwards, you can use options in Microsoft’s Productivity Power Tools.  This is a Visual Studio extension (accessible via Tools/Extension and Updates…). In all versions it has an option to copy code as HTML, amongst other things.

Unfortunately with Visual Studio 2010 and 2012 there’s no easy way to paste as HTML directly into the HTML editor in WordPress.  If you try you just get the text.

The trick here is to first paste into something that expects an HTML listing and will show all the tags as a result.  You can do this by adding an HTML page to your Visual Studio project and pasting into there.  The full steps to do this in any version of Visual Studio from 2010 onwards are below.

However, note that there’s an even easier way to do this in Visual Studio 2013 only (at the time of writing).  If you install the Productivity Power Tools 2013 in Visual Studio 2013 it puts an option on the edit menu ‘Copy Html Markup’.  If you select some code and then use this option you can paste directly into the HTML editor of your post in WordPress, and if you then switch to the visual editor you should see that the code is copied correctly.

The steps to get a code listing from Visual Studio 2010 or 2012 into WordPress in the same format as it is in Visual Studio are:

  1. Install the Productivity Power Tools in Visual Studio using Tools/Extension Manager.
  2. Add an HTMLPage item to your Visual Studio project
  3. Select the code you want to copy and hit Ctrl-C
  4. Go to your HTMLPage, right-click, Paste Alternate (not Paste: there should be a second paste option on the context menu).  This should show you the text with the HTML tags.
  5. Ctrl-A, Ctrl-C to select and copy the listing with the tags.
  6. Go to the HTML editor (‘Text’ tab at top) of your post in WordPress and paste the code in there at the appropriate point.

Below is an example of the results of this with a short method.  First what the end result looks like:

        static void MyMethod(int x, string y = "Hello"string z = "World") 
            Console.WriteLine(y + " " + z + ": " + x);

Then what the underlying HTML looks like.  You can tweak the generation of this in the Productivity Power Tools options but going with the defaults works fine for me:

<pre style="font-family:Consolas;font-size:13;color:black;background:white;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:blue;">void</span>&nbsp;MyMethod(<span style="color:blue;">int</span>&nbsp;x,&nbsp;<span style="color:blue;">string</span>&nbsp;y&nbsp;=&nbsp;<span style="color:#a31515;">&quot;Hello&quot;</span>,&nbsp;<span style="color:blue;">string</span>&nbsp;z&nbsp;=&nbsp;<span style="color:#a31515;">&quot;World&quot;</span>)&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af;">Console</span>.WriteLine(y&nbsp;+&nbsp;<span style="color:#a31515;">&quot;&nbsp;&quot;</span>&nbsp;+&nbsp;z&nbsp;+&nbsp;<span style="color:#a31515;">&quot;:&nbsp;&quot;</span>&nbsp;+&nbsp;x);

Delegate Syntax in C# for Beginners


I have been programming with C# since it came out but I still find the delegate syntax confusing.  This is at least partially because Microsoft have changed the recommended syntax regularly over the years.  This article is a quick recap of the various syntaxes.  It also looks at some of the issues with using them in practice.  It’s worth knowing about all the various syntaxes as you will almost certainly see all of them used.

This article is just a recap: it assumes that you know what a delegate is and why you’d want to use one.

.Net and Visual Studio Versions

The first thing to note is that you can use any of these syntaxes as long as you are using Visual Studio 2008 or later and targeting .Net 2.0 or later.

Named methods were available in .Net 1.0, anonymous methods were introduced in .Net 2.0, and lambda expressions were introduced in .Net 3.0.  However, like much of .Net 3.0, which is based on the .Net 2.0 assemblies, lambda expressions will compile to .Net 2.0 assuming you have the appropriate version of Visual Studio.

Note also that lambda expressions can do (almost) everything anonymous methods can do, and effectively supersede them as the preferred way of writing inline delegate code.


A listing of the code for this article is availableThe complete working program is also available.

The Delegate

For all of these examples we need a delegate definition.  We’ll use the one below initially.

        private delegate void TestDel(string s);

Named Methods

Named methods are perhaps the easiest delegate syntax to understand intuitively.  A delegate is a typesafe method pointer.  So we define a method:

        private void Test(string s)

Now we create an instance of our method pointer (the delegate above) and point it at our method.  Then we can call our method by invoking the delegate.  The code below prints out ‘Hello World 1’.  This is easy enough, but all a little cumbersome.

            TestDel td = new TestDel(Test);
            td("Hello World 1");

There’s one slight simplification we can use.  Instead of having to explicitly instantiate our delegate with the new keyword we can simply point the delegate directly at the method, as shown below.  This syntax does exactly the same thing as the syntax above, only (maybe) it’s slightly clearer.

            TestDel td2 = Test;
            td2("Hello World 2");

There is an MSDN page on named methods.

Anonymous Methods

The anonymous method syntax was introduced to avoid the need to create a separate method.  We just create the method in the same place we create the delegate.  We use the ‘delegate’ keyword as below.

            TestDel td3 = 
                delegate(string s)
            td3("Hello World 3");

Now when we invoke td3 (in the last line) the code between the curly braces executes.

One advantage of this syntax is that we can capture a local variable in the calling method without explicitly passing it into our new method.  We can form a closure.  Since in this example we don’t need to pass our string in as a parameter we use a different delegate:

        private delegate void TestDelNoParams();

We can use this as below.  Note that the message variable is not explicitly passed into our new method, but can nevertheless be used.

            string message = "Hello World 4";
            TestDelNoParams td4 = 

There is an MSDN page on anonymous methods.

Lambda Expressions

Lambda expressions were primarily introduced to support Linq, but they can be used with delegates in a very similar way to anonymous methods.

There are two basic sorts of lambda expressions.  The first type is an expression lambda.  This can only have one statement (an expression) in its method.  The syntax is below.

            TestDel td5 =  s => Console.WriteLine(s);
            td5("Hello World 5");

The second type is a statement lambda: this can have multiple statements in its method as below.

            string message2 = "Hello World 8";
            TestDel td6 =
                s => 
                    Console.WriteLine("Hello World 7");
            td6("Hello World 6");

Note that this example also shows a local variable being captured (a closure being created).  We can also capture variables with expression lambdas.

There is an MSDN page on lambda expressions.

Return Values

Nearly all of the examples above can be extended in a simple way to return a value.  The exception is expression lambda which cannot return a value. Doing this is usually an obvious change: we change our delegate signature so that the method it points to returns a value, and then we simply change the method definition to return a value as usual.  For example the statement lambda example above becomes as below.  The invocation of tdr6 now returns “Hello ” + message2, which we write to the console after the invocation returns:

            string message2 = "World 8";
            TestDelReturn tdr6 =
                s =>
                    Console.WriteLine("Hello World 7");
                    return "Hello " + message2;
            Console.WriteLine(tdr6("Hello World 6"));

The full list of all the examples above modified to return a value can be seen in the code listing in the method ExamplesWithReturnValues.


All of these syntaxes can be used to set up a method to be called when an event fires.  To add a delegate instance to an event we used the ‘+=’ syntax of course.  Suppose we define an event of type TestDel:

        private event TestDel TestDelEventHandler;

We can add a delegate instance to this event using any of the syntaxes in an obvious way.  For example, to use a statement lambda the syntax is below.  This looks a little odd, but certainly makes it easier to set up and understand event handling code.

            TestDelEventHandler += s => { Console.WriteLine(s); };
            TestDelEventHandler("Hello World 24");

Examples of setting up events using any of the syntaxes above can be found in the code listing.

Passing Delegates into Methods as Parameters: Basic Case

Similarly all of the syntaxes can be used to pass a delegate into a method, which again gives some odd-looking syntax.  Suppose we have a method as below that takes a delegate as a parameter.

        private void CallTestDel(TestDel testDel)
            testDel("Hello World 30");

Then all of the syntaxes below are valid:

            CallTestDel(new TestDel(Test));  // Named method
            CallTestDel(Test);               // Simplified named method
            CallTestDel(delegate(string s) { Console.WriteLine(s); });  // Anonymous method
            CallTestDel(s => Console.WriteLine(s));  // Expression lambda
            CallTestDel(s => { Console.WriteLine(s); Console.WriteLine("Hello World 32"); });  // Statement lambda

Passing Delegates into Methods as Parameters: When You Actually Need a Type of ‘Delegate’

Now suppose we have a method as below that expects a parameter of type Delegate.

        private void CallDelegate(Delegate del)
            del.DynamicInvoke(new object[] { "Hello World 31" });

The Delegate class is the base class for all delegates, so we can pass any delegate into CallDelegate.  However, because the base Delegate class doesn’t know the method signature of the delegate we can’t call Invoke with the correct parameters on the Delegate instance.  Instead we call DynamicInvoke with an object[] array of parameters as shown.

Note that there are some methods that take Delegate as a parameter in the framework (e.g. BeginInvoke on a WPF Dispatcher object).

There’s a slightly unobvious change to the ‘Basic Case’ syntax above if we want to call this method using the anonymous method or lambda expression syntax.  The code below for calling CallDelegate with an expression lambda does NOT work.

            CallDelegate(s => Console.WriteLine(s));  // Expression lambda

The reason is that the compiler needs to create a delegate of an appropriate type, cast it to the base Delegate type, and pass it into the method.  However, it has no idea what type of delegate to create.

To fix this we need to tell the compiler what type of delegate to create (TestDel in this example).  We can do this with the usual casting syntax (and a few more parentheses) as shown below.

            CallDelegate((TestDel)(s => Console.WriteLine(s)));  // Expression lambda

This looks a little strange as we don’t normally need a cast when assigning a derived type to a base type, and in any case we’re apparently casting to a different type to the type the method call needs.  However, this syntax is simply to tell the compiler what type of delegate to create in the first place: the cast to the base type is still implicit.

We need to do this for any of the syntaxes apart from the very basic named method syntax (where we’re explicitly creating the correct delegate):

            CallDelegate(new TestDel(Test));  // Named method
            CallDelegate((TestDel)Test);      // Simplified named method
            CallDelegate((TestDel)delegate(string s) { Console.WriteLine(s); });  // Anonymous method
            CallDelegate((TestDel)(s => Console.WriteLine(s)));  // Expression lambda
            CallDelegate((TestDel)(s => { Console.WriteLine(s); Console.WriteLine("Hello World 32"); }));  // Statement lambda


There is one further simplification that we can use in the examples in this article.  Instead of defining our own delegates (TestDel etc.) we can use the more generic Action and Func delegates provided in the framework.  So, for example, everywhere we use TestDel, which takes a string and returns void, we could use Action<string> instead, since it has the same signature.

Why Some Password Security is a Waste of Time


This is very off-topic, but a recent MSDN article and a paper it referenced got me thinking about password security in our organization.  If my maths is right, the costs of the way we do this are huge.

Changing Passwords Monthly

I work for a very large bank (it has about 300,000 employees, or did have before the banking crisis).  Until recently this bank forced us to change our passwords monthly.  We have two passwords: Windows and ‘single sign on’.  These are the internal passwords we use to do our jobs.  The Windows one is used to log on to Windows obviously.  The single sign on password is to access almost any other internal resource: the timesheet system, the project management system, the issue tracking system, the performance management system etc. etc.

So I had to change both these passwords every month.  Let’s say that on average I can invent a new password, commit it to memory, and enter the old one and the new one twice in 30 seconds, allowing for getting it wrong occasionally.  If all 300,000 employees spend that long changing their two passwords monthly I reckon we spent roughly 35 working years per annum on this (2 x 0.5 x 12 x 300000 / (60 x 7 x 240)).

Internet Companies DONT Make You Change Your Password

Now, I have a number of online bank accounts and none of them expect me to change my password regularly.  Nor do any of the shopping sites that have my credit card details.  The reason for this is that if someone gets hold of my password it really doesn’t matter if I’m forced to change it a week later.  The thief is going to use it straightaway if they are going to use it at all.  The security controls need to prevent them getting hold of the password in the first place.

So why do it for passwords in a big organization?  There are some reasons I can think of, but are they worth the cost?

To be fair, the bank has realized this and reduced the frequency with which passwords have to be changed to 90 days.  This obviously cuts the cost by a factor of three so we now only spend about 12 working years per annum on this.  However, my personal opinion is that this is a control that could be removed completely.

Passwords for Every Application with Timeouts

Another bugbear is that our ‘single sign on’is far from ‘single’.  Every application we use forces us to enter it separately, and they are all set to time out after a short period of inactivity, not exceeding 30 minutes.  This is mandatory as part of our security policy.  Because this password is used for all our internal systems we all log into them frequently.  I estimate I enter this password about 10 times a day, and I expect that isn’t far from the average for the organization as a whole.

The estimated cost if everyone is doing this, assuming it takes me 15 seconds to enter my password (including periodically mistyping the mandatory capital letter) is about 1800 working years per annum (10 x 15 x 240 x 300000 / (60 x 60 x 7 x 240)).  Ouch.

So our organization spends 1800 working years per annum just logging in to systems.  This is a global organization, so it’s hard to know what rate to use to work out the cost of that.  However, even at the federal minimum wage of $7.25 per hour that’s $22 million.  I suspect an accurate fully-loaded cost would be several times that.

There is some momentum for changing this, at least in our group, since the benefits of kicking everyone out of an internal system after a few minutes of inactivity are even less clear than for password changing.


An organization with 300,000 employees changing two passwords monthly spends about 35 working years per annum on this activity.

The same organization with a security policy that compels every internal application to use a password-based login, and then logging everyone out after a short period of inactivity, spends about 1800 working years per annum on this activity.

These are large numbers and it’s not entirely clear that the cost justifies the saving in terms of more secure systems.

I’ll write about C# and derivatives again soon.

Blurry Text with Small Fonts in WPF


The difficulties with text rendering in WPF have been well documented elsewhere.  However, every time I get a blurry button I can’t remember how to fix it.  This brief post shows the usual solutions.


With small font sizes the default WPF text rendering can lead to text looking very blurry.  This is particularly a problem on controls (e.g. text on buttons), where we often use small fonts.

In .Net 4 Microsoft finally gave us a solution to this problem, which is to set TextOptions.TextFormattingMode = “Display” (instead of “Ideal”).  This snaps everything to the pixel grid.  However, this mode doesn’t look good at large text sizes, so there’s no easy solution to this problem.

Other TextOptions

Other TextOptions are

1.  TextHintingMode (Animated/Auto/Fixed)

This just tells the renderer to use smoother but less clear rendering for animated text.  It won’t fix the blurry text problem for static text (which should have Auto or Fixed set).

2.  TextRenderingMode (Aliased/Auto/ClearType/GrayScale).

Tells the renderer how to draw.  This DOES affect blurriness.  In particular using Aliased rather than the default Auto can be good at small sizes.

Effect of These Options

Below, with font size 12, the first line is the default (Ideal/Auto).  This is quite blurry.  The second line is Display/Auto (less blurry) and the third line is Display/Aliased (not at all blurry, but a bit jagged).  The second two lines are the options usually used to fix the problem.

This is the same but at font size 24, which highlights the problem since now Ideal/Auto (the first line) probably is ideal: