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 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
By Month: November 2022, October 2022, August 2022, February 2021, January 2021, December 2020, November 2020, March 2019, September 2018, June 2018, May 2018, April 2018
Apple, C#, Databases, Faircom, General IT Rant, German, Informatics, LINQ, MongoDB, Oracle, Perl, PostgreSQL, SQL, SQL Server, Unit Testing, XML/XSLT
Leave a Reply