FormatException in WPF DataBinding

While working on some F#/C# WPF code the other day, I kept hitting a fatal FormatException when running under the debugger. Annoyingly, the app would quit with:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.

But it worked fine when started from Expression Blend, or when run using Start Without Debugging in Visual Studio. Let’s take a closer look…

Looking at the output window, there seemed to be an intial exception before the FormatException, and from the stack trace the second one seemed to be generated as WPF was trying to log the first one:


I had a look at the text of the first exception, and from that it was obvious:

Unable to cast COM object of type 'System.__ComObject' to interface type 'IWhatever'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{CAD939D0-5E5D-11D7-AA0B-0002B33FE9DX}' failed due to the following error: Bad variable type. (Exception from HRESULT: 0x80020008 (DISP_E_BADVARTYPE)).

The message contains curly brackets around the IID, and they’re being intrepreted as insertion points by a call to String.Format!


So that explained why it only happens in debugger runs; as this post helpfully points out the WPF databinding is enabled by default in that case. To workaround it, you can disable logging programmatically or using the App.config file to only display Critical output. So if your app is named foo.exe, create a file foo.exe.config that contains:

      <source name="System.Windows.Data" switchName="SourceSwitch"/>
      <add name="SourceSwitch" value="Critical" />


Hopefully there’ll be a fix for this at some point soon, as disabling the logging is a pretty large hammer to crack this small nut.