C# Often Surprises Me, part: 000001

The C# specification is clear, the language documentation second to none, and there are few surprises about language behaviour or .Net framework on a day in/out basis.

But, and there are no points to see where this is going,  I had a recent requirement to debug some C# code that automated a piece of laboratory instrumentation. The third-party proprietary library that performed the automation provided a method that returned a status code, a number that should be cast to a UInt16 for manipulation. Each bit in this number represented some instrument status value.

I have written the most trivial C# code example that shows a typical scenario, namely that the status code is assigned, and then interpreted.

using System;
namespace ConsoleApplication1076
{
   class Program
   {
      [Flags]
      public enum InstrumentStatus : UInt16
      {
         Idle = 0x01,
         Running = 0x02,
         Waiting = 0x04,
         Processing = 0x08,
         Flood = 0x010,
         CleanCycle = 0x020,
         Error = 0x080
      }

      static void Main(string[] args)
      {
       UInt16 instrumentCode = 6; //hardcoded to 6 here but in production code, the value was returned by some C++ COM component
       String status = String.Format("Instrument Status: {0}", (InstrumentStatus)instrumentCode);
      }
   }
}

Here is my surprise:

  • The String status has the value “Instrument Status: Running, Waiting“.
  • The String status does not have the value “Instrument Status: 6“.

The key to the observed behaviour is the Flags attribute on the enum. Typical of Microsoft documentation, this functionality is documented in their example usage code too.  I had also expected to write some crappy code to query each bit of the number returned to build up the enum, with values and hardcoded descriptions. Nope – more work I just don’t have to do. It is really hard not to be continually impressed with .Net.

— Published by Mike, 11:23:21 17 September 2016

Leave a Reply