Do I use a ‘switch’ or sequential ‘if’s? A shallow dive into their CIL

I recently found myself needing to convert a calculation on ints to use double values. One of the functions within this calculation was a switch statement and as switch only supports integral types, this needed more than just a type change.

I was fortunate in that this particular double value was always at most one decimal place which left me with two possible options; either replace the switch with a bunch of sequential if statements or multiply the double by 10, cast it to an int and switch on the resulting int.

Ignoring the debate over whether the cast is a bit too hacky, it got me thinking; what is the difference in compiled output (CIL) between switch and sequential ifs covering the same test cases? Given that the cases of a switch are compile time constants and together as a block, does the compiler make any attempt to optimise the comparison or does it just grind through all the cases linearly until a match is found (making it essentially syntactic sugar for sequential ifs).

Out came a test project and ILSpy and this is what I found.

Here’s the test code and corresponding annotated CIL (Release build, .Net 4.5):

Although only a single example for my very simple use case, the only significant difference between the two compiled outputs is that the switch example uses beq.s positive comparison (equals) and the if example uses bne.un.s negative comparison (not equals) to achieve the same result. Because of this, in the scenario where no match is made the switch example involves executing one more instruction.

Will the extra instruction be make or break for the performance of your application? Certainly not, but contrary to the spirit of endless abstraction I find it grounding to occasionally head in the opposite direction and see what even the most basic of language constructs represent under the hood.

As far as I can see in this case the only real argument is that of code legibility. Now I know…

Tagged , , , , , , , ,

UPDATE if exists, INSERT if not in MySQL (AKA the UPSERT)

It’s a bit of a long running joke that I’m not really a database guy, but let’s just say that lately I’ve been exposed to a little more DB than usual and it’s been quite a steep learning curve.

Anyway, this little feature in MySQL has proved pretty useful to me so I thought I’d make a note of it on my in-lieu-of-a-functioning-memory blog.

As the title says, what if you want to  combine the Create and Update from your CRUD code in one query; say you’re performing an INSERT with a nested SELECT to insert more than one row, but there’s a chance that one of these inserts breaks a unique key constraint somewhere and so you want to UPDATE in that case instead?

This is where INSERT … ON DUPLICATE comes to the rescue.

How to create an array with a lower bound other than zero in .Net

Did you know that you can create an Array with a lower bound other than zero in .Net?

A good friend of mine (cheers Jarek) showed me this a while back. I’m still yet to find a real-world application but it’s interesting all the same.

Array has a method called CreateInstance, which is useful if you want to create an Array during run-time of a Type which might not be known beforehand. This will create an array of integers with length 5:

One overload also lets you specify the lower bounds of the array. It is used to create multi-dimensional arrays, so you pass in arrays of lengths and bounds. This will create an array of integers, with length 50, indexed from 10.

I suppose this may come in useful when trying to model an existing offset numbering scheme in your domain, but has anyone come across this or used it before?

Tagged , , , , , ,

Silly for loop syntax

I’ve been working with C-style languages for over 12 years now, but stumbled across this funny for loop syntax in a code tutorial today and had to double-take:

Although technically correct, quite what you gain from putting the iterator within the condition apart from confusion is lost on me.

Tagged , , , , , , , ,

A PRISM Notifying Backing Property Snippet for Visual Studio

When writing View Models deriving from NotifyingObject in PRISM I find myself endlessly having to write public notifying properties backed by private fields. To save my fingers, here’s a Visual Studio snippet I use:

To use it:

  • Copy and paste the xml into a new file.
  • Save it as “PRISMNotifyingBackedProperty.snippet”.
  • In Visual Studio open the Code Snippet Manager (Tools -> Code Snippets Manager).
  • Click the Import button and navigate to the file you saved.
  • When it prompts you where to add the snippet, chose My Code Snippets, click Finish, then OK.

You can now type “propprism” into your code and hit Tab to insert the snippet.

Hope this helps.

Tagged , , , , , , ,

So long… and thanks for all the Red Bull

Today was my last day at Red Bull Technology. For the past three years I’ve been working for the quadruple double championship winning Formula One team and I must admit, I’m going to miss it.

Infiniti Red Bull Racing logo

I feel proud to have worked in such a fascinating industry, learning new tools and technologies with some of the most hard-working, talented and dedicated people I’ve ever met. I never followed F1 before joining but I’m definitely a fan now. It’ll be strange watching the sessions without supporting my software but I know it’s in good hands. I look forward to watching the seasons unfold, and hopefully more double championship wins for Red Bull! 2014 is certainly going to be an interesting season for everyone involved so I wish them every luck.

Infiniti Red Bull Racing Pit Wall

My career so far has taken me from central government communications via industrial control systems to F1, they’ve all involved software engineering, and for the past 7 or so years .Net, so what’s in store for me next?

Career So Far Icons

My future employer would rather I not name them, which is fine by me. The bright lights of London are my next destination; swapping the M1 and the stupidly impractical car for the 0700 train from Northampton, a whole new industry and domain to get my head around, and a new team to work with and learn from. I’m still in software, and still very much .Net so some things don’t change, but I’m very excited by the new challenge and looking forward to starting on the 20th January. One upside of my new train commute is that I’ll get some more time to work on blogging and personal projects so armed with my new toy I hope to manage a few more blog posts this year.

To all of my former colleagues at RBR/RBT, again, thank you for such an amazing time, and good luck in the future!

Tagged , , , , ,

3 for 1 MCSD Microsoft Exam Promotion

Microsoft Virtual Academy has just launched a new exam certification promotion; 3 for 1 on all of their exams which count toward the following Microsoft Certified Solutions Developer (MCSD) certifications:

Only available until 31st May 2014, click here for more info and to book.

As I’ve previously blogged about, here, here and here, I’ve taken a few of these exams across both the HTML5 and C# Windows Store certifications and found them really good for both validating existing knowledge, filing in gaps and learning completely new stuff so would highly recommend them.

Tagged , , , , , , , , ,

How to debug JavaScript in a Visual Studio 2013 ASP.NET Web Application

I’ve been struggling trying to debug my JavaScript in ASP.Net Web Applications under Visual Studio 2013, it lets me place a breakpoint in the script:

Placing a breakpoint

But then I hit F5 to run my application under the debugger and it gives me “The breakpoint will not currently be hit. No executable code of the debugger’s target code type is associated with this line”:

Breakpoint error

Which is a bit rubbish. I’m sure they have their reasons for letting me place a breakpoint and then so cruelly toying with my emotions in this way but still, it doesn’t help me single-step through the nail-biting outcome of my (a < b) conditional, which is frustrating to say the least.

Although not ideal (as it involves making code changes to your code), you can cause Visual Studio to break during execution by adding the keyword


to your code like this:

Adding the debugger keyword

Fire up the debugger again and you’ll find it break at the line.

Visual Studio breaking at the debugger line

It seems to strip out any syntax highlighting while its in this state but at least you can hover over fields to see their value and use the Immediate Window and all the usual Debugger trickery pokery without having to resolve to something like Firebug or IE’s F12 Developer Tools.

A big shout out to my good friend Jarek for showing me this. Check out his awesome productivity extension for Visual Studio, VSCommands.

Tagged , , , , , , , , , , ,

How to stop Lego’s Life of George iPhone and iPad app from crashing

Lego Life of George ScreenshotFor those of you who know me it’s no surprise that I’m a big kid with a borderline unhealthy fascination with Lego, so when Mrs Santa very kindly brought me the Lego Life of George game this year you can understand my disappointment to download the iOS app on my iPhone only to find it consistently crash on startup rendering the whole thing pretty useless.

Same story on my iPad and no matter how many times I restarted or closed all other apps. It’s understandably getting quite a lot of bad reviews on the App Store with people threatening to return it.

Anyway, until Lego sort this out you can get the app working (albeit with all the online functionality disabled) if you put your device in airline mode.

Hope this helps any other kids out there (both big and small 🙂 ).

Tagged , , , , , , ,

Introduction to Caliburn.Micro on Windows Phone 8

I thought I’d try something different with my latest home software project; after writing a “ViewModelBase” INotifyPropertyChanged implementation for the millionth time (I really should start creating some shared libraries) I decided to have a look at one of many MVVM libraries out there and stumbled across Caliburn.Micro. Here are some newbie notes on my experiences.

Windows Phone 8 Support
I’m writing a Windows Phone 8 application, so fell at the first hurdle after installing the package through nuget and following the tutorial here. This doesn’t work under WinRT and so my attempts at using the generic form of Bootstrapper were met with

The non-generic type ‘Caliburn.Micro.Bootstrapper’ cannot be used with type arguments.

instead you need to derive from PhoneBootstrapper to end up with something looking like this:

Which you can then use as a standard template bootstrapper.

Views and ViewModels

Caliburn.Micro applies a View-Model First approach wiring up its Views and ViewModels though a naming convention. If you put all of your Views in a folder called \Views and all of your ViewModels in a folder called \ViewModels under your project root you can then register your ViewModel with the container in your bootstrapper (as I have done with MainPageViewModel in the code above) and it will automatically look for a view called MainPage.xaml in the \Views folder. I quite like this as it matches my usual folder structure for an MVVM project and takes away some of the leg work.

The container can either register services PerRequest, where a new instance is created every time it is requested, or Singleton which will return the same single instance to each request.

Caliburn.Micro will automatically set the DataContext of the View to the appropriate ViewModel. It provides a base class PropertyChangedBase to derive your ViewModel classes from which handles the usual INotifyPropertyChanged stuff and provides a NotifyOfPropertyChange method which can either take a property name String or an Expression to represent the property like this:

The advantage of using the expression is that if you rename the property and forget to update the name in the expression, this will result in a compilation error, rather than a run-time binding error if you used a string. Visual Studio’s Rename function will also know to change this.


With your Views and ViewModels wired up magically as above, Caliburn.Micro then provides you with some nice shorthand for DataBinding. It’s important to point out that all of the usual {Binding} syntax works as well.

If we had a TextBlock in MainPage.xaml and wanted it to show the text contained in the MyString property on MainPageViewModel.cs we can simply do this:

Which is pretty handy, although seems to run out of steam as soon as you want any more complicated binding. If I wanted to not only bind the text to MyString but the foreground colour to another property on my ViewModel you can fall back to the standard Binding markup extension and use both like this:


Commands have also been simplified by Caliburn.Micro, let’s dive straight in with an example. A Button on my MainPage.xaml defined like this:

Will call the method ShowMyString on the MainPageViewModel.cs on click.

This is again quite powerful, but worth bearing in mind that by default will wire up every event on the element to that method. If you want further control, you can use the following syntax to explicitly wire up just the Click event:

You can pass parameters into the method like this:

Which will pass a reference to the UI element the action is attached to. Other parameters are as follows:

  • $eventArgs – The EventArgs or input parameter for your action.
  • $dataContext – The DataContext of the element that the action is attached to.
  • $source – The FrameworkElement that triggered this action.
  • $view – The View that is associated with this ViewModel.
  • $eventArgs – The EventArgs or input parameter for your action.

To hook into the CanExecute part of ICommand you simply create a method called CanShowMyString() in your ViewModel (just prefix the execute method name with “Can”). To update this and ensure that the CanExecute is re-evaluated make sure you call:

where appropriate.


And that concludes my first quick look at Caliburn.Micro. There are lots more to it than I’ve covered here but you can see how the “magic” can make for some very powerful yet clear and easy to maintain (once you know what its doing) MVVM abstraction. I’ll keep playing and post a follow-up article when I get further along with my app.

Tagged , , , , , , , , , , , , , ,
%d bloggers like this: