Using extension methods in C# to expand external libraries

Using extension methods in C# to expand external libraries
Indypendenz / Shutterstock

Extension methods are a great way of advancing an existing library without modifying the original class. But it is possible to do something even more powerful with it. Even the dlls of a closed source commercial library can be extended. Halcon is a commercial computer vision library which will be used for showcasing this application.

HImage is a class available in the mentioned library which allows reading, creation and manipulation of images as well as extraction of some features. Even though Halcon has many features used in computer vision, sometimes it requires some customization. For the purposes of adapting exposure time, it would be practical to have the number of overexposed pixels. The end result would be a method name shown in IntelliSense with a dashed arrow like in an image below.

The implementation requires modifier “this” to be added before the first parameter and the method has to be static in a static class.

For a deep dive in extension methods you can see the free preview of Jon Skeet’s book C# in Depth